Ruby - Converting Image Formats

September 21, 2014

So my streak has been broken, in total I have missed three days of posting. Last week Saturday I was man down after flying from San Francisco to Bermuda and this weekend has been crazy with work and a lack of sleep. It is clear I need to take my own advice and get some rest.

However, tonight I want to share a cool way to convert from one image format to another. RMagick is a binding from Ruby to the ImageMagick and GraphicsMagick image manipulation libraries. ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PNG, Postscript, SVG, and TIFF. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.

Now let’s go ahead and convert a PNG to JPG. This is our image:

cat png

First make sure you have installed ImageMagick from their website. Next go ahead and install the RMagick gem which is a Ruby binding to ImageMagick.

gem install rmagick

Next we can create a script file to hold our code, the first line will be a require statement to ‘rmagick’. Let’s have a look at the complete code and talk through it.

The code is straightforward; the only thing that tripped me up was when calling RMagick’s read method it returns an array so make sure you call first or use the appropriate index for the image you want.

The code above shows how we read in the image from the disk. To convert this image, you call the write method passing in the new filename including the extension.

After the code has run we are let with a new cat file which is a jpg:

cat png

To show you that this works correctly, I went ahead and read the newly created image and print out its format. This is a nice little utility that I have been using to convert quickly between different formats. The cool thing is that Magick supports a bunch of different file formats, so, checkout their site.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus