Skip to content

Improving ImageMagick performance

Janko Marohnić edited this page Apr 19, 2018 · 2 revisions

JPEG hints

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. For large images this can greatly reduce memory usage and increase processing speed of the ImageMagick command. To reduce JPEG artifacts, it's recommended to specify dimensions that are at least twice as large as the intended thumbnail dimensions.

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

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)

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*2}x#{height*2}" } })
    .resize_to_limit!(width, height)

  hash.merge!(name => thumbnail)
end