Class: Sprockets::ImageCompressor::PngCompressor

Inherits:
Base
  • Object
show all
Defined in:
lib/sprockets/image_compressor/png_compressor.rb

Instance Method Summary collapse

Methods inherited from Base

#binary_path

Constructor Details

#initializePngCompressor

Returns a new instance of PngCompressor.



6
7
8
# File 'lib/sprockets/image_compressor/png_compressor.rb', line 6

def initialize
  @name = "pngcrush"
end

Instance Method Details

#compress(content) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sprockets/image_compressor/png_compressor.rb', line 10

def compress(content)
  compressed_png_data = ""
  Tempfile.open ["in_file", ".png"] do |in_file|
    in_file.binmode
    out_file_path = in_file.path + ".optimized.png"
    in_file.write content
    in_file.close

    out = `#{binary_path} #{in_file.path} #{out_file_path} 2>&1`

    File.open out_file_path, "rb" do |out_file|
      compressed_png_data = out_file.read
    end
    File.unlink out_file_path
  end
  compressed_png_data

rescue Errno::ENOENT => e
  # error during compression so out_file not found
  # return original content as a fallback
  warn "sprockets-image_compressor: PNG compression failed... returning original."
  content
end