Search code examples
ruby-on-railsrubyimagemagickminimagick

Resizing an image with mini_magick


My service has both a web version and an iPhone version. On the iPhone, we ensure that users submit a square version by having it crop when it uploads. We are allowing uploads on the website as well, but we do not have such a feature.

As such, I would like to scale any uploaded image into fitting a 612 * 612 area. What would be the best way to accomplish this?

I am using Ruby / mini_magick


Solution

  • You'd just use the resize method from MiniMagick, there's an example on the Github page:

    https://github.com/minimagick/minimagick

    Presumably you have the image as a bunch of bytes in memory so something like this:

    image = MiniMagick::Image.read(your_image_bytes)
    image.resize('612x612')
    scaled_image_bytes = image.to_blob
    # Or image.write(filename)
    

    MiniMagick uses standard ImageMagick geometry strings for sizing and, from the fine manual, a WxH geometry:

    Maximum values of height and width given, aspect ratio preserved.

    so using '612x612' will scale the image to fit within a 612px square while preserving the aspect ratio.

    You could also use Jcrop to allow your web users to crop the their uploaded images to fit into a square.