Image Manipulation with Ruby gem MiniMagick

Moin Moin,

in a recent project, I have to resize uploaded images because the images have to be shown in a gallery. The user who uploads the image likes comfort, so I started to use

https://github.com/jnicklas/carrierwave

for handling the upload and

https://github.com/probablycorey/mini_magick

to resize the images in the upload process. MiniMagick is a wrapper for the cli tool

ImageMagick

well known for its huge image editing possibilities

If you just need basic resizing, carrierwave can do the job for you as well.

Here’s a simple example (taken from the github site). The script is called magic.rb and there is a image called input.jpg in the same folder. where I run the script:

#!/usr/bin/env ruby

require 'rubygems'
require 'mini_magick'

image = MiniMagick::Image.open("input.jpg")
image.resize "100x100"
image.write  "output.jpg"
puts "width: #{image[:width]}"
puts "height: #{image[:height]}"
puts "compression: #{image["%Q"]}"

The output is:

duke@Macintosh:~/workspace/programming/ruby/MiniMagick$ ./magic.rb
width: 71
height: 100
compression: 99

Simple! But the one thing I wanna point you to is the following line in magic.rb:

puts image["%Q"]

This is cool, because you can use the format options provided by ImageMagick. You can find a list of all options at

http://www.imagemagick.org/script/escape.php.

So again a cool gem which saves hours of work!

Cheers

Andy

Published: December 10 2011