Skip to content

Improving ImageMagick performance

Janko Marohnić edited this page Mar 26, 2018 · 2 revisions

When generating thumbnails from a JPEG image, you can give a hint to the JPEG image library to load only the portion of the image necessary (which would be the dimensions of the largest thumbnail you want to generate). For large images this can greatly reduce memory usage and increase processing speed of the ImageMagick command.

pipeline = ImageProcessing::MiniMagick
  .source(image)
  .loader(define: { jpeg: { size: "800x800" } })

large  = pipeline.resize_to_limit!(800, 800)
medium = pipeline.resize_to_limit!(500, 500)
small  = pipeline.resize_to_limit!(300, 300)
icon   = pipeline.resize_to_limit!(150, 150)
# https://gist.github.com/janko-m/3ad5aa4341d97a16beb16feeef106b79
Without JPEG hints: 2.34s
With JPEG hints:    0.93s

If you want to improve performance even further, you can specify JPEG hints for each thumbnail individually:

definitions = {
  large:  [800, 800],
  medium: [500, 500],
  small:  [300, 300],
  icon:   [150, 150],
}

definitions.inject({}) do |hash, (name, (width, height))|
  thumbnail = ImageProcessing::MiniMagick
    .source(image)
    .loader(define: { jpeg: { size: "#{width}x#{height}" } })
    .resize_to_limit!(width, height)

  hash.merge!(name => thumbnail)
end
With JPEG hints:            0.93s
With individual JPEG hints: 0.65s

Clone this wiki locally