Skip to content

Commit

Permalink
Faster PNG striping
Browse files Browse the repository at this point in the history
I found that when the image is really big the ChunkyPNG gem is slow to
encode/decode the PNG pixels. As we only want to strip the metadata we
can work in the Datastream that doesn't transform the pixels.

With my test image this method went from 10s to 0.01s.
  • Loading branch information
rafaelfranca committed Sep 13, 2016
1 parent 9cca48e commit 270cf5d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
12 changes: 9 additions & 3 deletions lib/sprockets/svg.rb
Expand Up @@ -18,9 +18,15 @@ def self.convert(svg_blob)
end

def strip_png_metadata(png_blob)
image = ChunkyPNG::Image.from_blob(png_blob)
USELESS_PNG_METADATA.each(&image.metadata.method(:delete))
image.to_blob
image = ChunkyPNG::Datastream.from_blob(png_blob)

image.other_chunks.reject! do |chunk|
chunk.respond_to?(:keyword) && USELESS_PNG_METADATA.include?(chunk.keyword)
end

str = StringIO.new
image.write(str)
str.string
end

def install(assets)
Expand Down
2 changes: 0 additions & 2 deletions spec/rails_spec.rb
Expand Up @@ -52,8 +52,6 @@
png_metadata = ChunkyPNG::Image.from_file(png_path.to_s).metadata
expect(png_metadata).to be_empty

# Metadata usually contains some timestamps, so sleeping is the best way to make sure they are all stripped
sleep 1
expect(png_fingerprint).to be == Digest::MD5.hexdigest(Sprockets::Svg.convert(svg_path.read))

expect(manifest['files'][svg_name]).to be_present
Expand Down

0 comments on commit 270cf5d

Please sign in to comment.