Class: PngQuantizator::Image
- Inherits:
-
Object
- Object
- PngQuantizator::Image
- Defined in:
- lib/png_quantizator.rb
Instance Method Summary collapse
-
#initialize(file_path) ⇒ Image
constructor
A new instance of Image.
- #quantize!(colors = 256) ⇒ Object
- #quantize_to(destination_path, colors = 256) ⇒ Object
Constructor Details
#initialize(file_path) ⇒ Image
Returns a new instance of Image.
12 13 14 15 16 |
# File 'lib/png_quantizator.rb', line 12 def initialize(file_path) raise ArgumentError, "could not find #{file_path}" unless File.file?(file_path) @file_path = file_path end |
Instance Method Details
#quantize!(colors = 256) ⇒ Object
18 19 20 21 22 23 24 25 26 |
# File 'lib/png_quantizator.rb', line 18 def quantize!(colors = 256) Tempfile.open([SecureRandom.hex(16), ".png"]) do |file| quantize_to(file.path, colors) FileUtils.cp(file.path, @file_path) file.close true end end |
#quantize_to(destination_path, colors = 256) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/png_quantizator.rb', line 28 def quantize_to(destination_path, colors = 256) raise PngQuantError, "pngquant not found in PATH=#{ENV['PATH']}" unless which("pngquant") exit_code, err_msg = Open3.popen3("pngquant #{colors}") do |stdin, stdout, stderr, wait_thr| stdin.write(File.read(@file_path)) stdin.close File.open(Shellwords.escape(destination_path), "w") do |f| f.write stdout.gets(nil) f.flush end stdout.close = stderr.gets(nil) stderr.close [wait_thr.value, ] end raise(PngQuantError, err_msg) if exit_code != 0 true end |