Stefan Wille

About MeCVContactImpressumDatenschutz

Creating smaller images in Rmagick

November, 15 2011

When you create an image in Rmagick and save it, chances are high that your image will be way too big. The reason is that, by default, Rmagick creates uncompressed images.

Try to run optipng <filename> for PNG or jpegoptim --strip-all <filename> for JPG on your file, and you will probably see a file size reduction of 20% - 90%. That is without loosing image quality! One way to improve on this is to set the compression level in Rmagick's write method. Here is some clunky code to do this:

compression =
  case image_file_name
  when /(jpg)|(jpeg)$/i
    Magick::LosslessJPEGCompression
  when /png$/i
    Magick::ZipCompression
  else
    nil
  end
image.write(output_file_name) do
  self.compression = compression if compression
end

The results are not as good as with the command line tools, but definitely better than uncompressed images. If your images are part of a web page, then you can reduce your page load time by reducing image size. To me this was a big deal on my current project.