Search code examples
rubyminimagick

Make Multiple Copies From Original with image = MiniMagick


I need to generate several copies of an image in different formats/sizes. Can I do it without re-opening the source for each format/size?

Take this example:

# Original image is jpeg
image = MiniMagick::Image.open url
image.crop dimensions
image.format 'pdf'
upload image
# image = MiniMagick::Image.open url # No! Needless network traffic and processing.
image.format 'png'
image.resize new_size
upload image

This code is no good without the second #open because when image.format 'png' is called the image is a PDF, so I would end up rasterizing it, which is not what I want to do.

There's a method #clone, but it does not make a clone of the image object. Rather it sets a parameter for the converter. I can't figure out if this will somehow suit my purpose.


Solution

  • I found one way to do it, which seems fine.

    # Original image is jpeg
    image = MiniMagick::Image.open url
    image.crop dimensions
    
    new_image = MiniMagick::Image.open image.tempfile.path
    
    image.format 'pdf'
    upload image
    
    new_image.format 'png'
    new_image.resize new_size
    upload new_image
    

    Both the PDF and PNG will be cropped but each will only be converted once.