Class: PngQuantizator::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/png_quantizator.rb

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Image

Returns a new instance of Image.

Raises:

  • (ArgumentError)


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

Raises:



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
    error_message = stderr.gets(nil)
    stderr.close

    [wait_thr.value, error_message]
  end

  raise(PngQuantError, err_msg) if exit_code != 0
  true
end