September 19th, 2005

Custom Image Overlays With RMagick

2 comments on 1347 words

!http://encytemedia.com/blog/files/rmagick-plus-equal.png(Custom Overlays with RMagick)!

RMagick is an interface between the Ruby programming language and the ImageMagickTM and GraphicsMagick image processing libraries.

“Stylegala”:http://stylegala.com uses a similar style to decorate the images on their site. They use a slightly different technique which I’m not going to go into here because we want to have fun with RMagick. :-)

First the code:

1
2
3
4
5
6
7
8
9

require 'RMagick'
include Magick

images = ImageList.new("images/apple.gif", "images/overlay.png")
images[0] = images[0].crop(Magick::CenterGravity, 115, 86)
images[0].page = Rectangle.new(images[1].columns, images[1].rows, 0, 0)
images[0].background_color = "white"
images.flatten_images.write("test.png")

First we create a new @ImageList@ object and load in our two images. Because @flatten_images@ takes the last image in the ImageList array when flattening, it’s important that we load the overlay image last.

1
2

images = ImageList.new("images/apple.gif", "images/overlay.png")

@ImageList@ automagically creates new @Image@ objects for each image we provide as an argument. This means all the “methods”:http://studio.imagemagick.org/RMagick/doc/image1.html and “attributes”:http://studio.imagemagick.org/RMagick/doc/imageattrs.html of @Image@ are available at our disposal.

Now we set the @page@ attribute for our apple image so it will match up in width and height to our overlay image.

1
2

images[0].page = Rectangle.new(images[1].columns, images[1].rows, 0, 0)

The @page@ attribute accepts a @Rectangle@ object. We create a @Rectangle@ with the same width and height of our overlay image (columns and rows are equal to width and height in pixels). The last two arguments are the x and y(top, left) offsets. Since we don’t need to offset our apple image any, we’ll set these to 0.

Now we set the background color of our apple image.

1
2

images[0].background_color = "white"

Why do we need to do this? Because we really never resized the apple image when we modified it’s page attribute, rather we padded the edges to match our overlay image’s width and height. If we don’t set the background color explicitly to white then it will have a pail white look (Remove it and see for yourself.)

Finally we flatten the images and write a single image to the file system.

1
2

images.flatten_images.write("test.png")

Discussion

  1. topfunky topfunky said on September 27th

    Sweet.

    I assume you use a transparent PNG for the overlay?

  2. Justin Palmer Justin Palmer said on September 28th

    Thanks Geoffry, yes that would be a transparent .png file. Guess I should probably add that little detail ;-)

Sorry, comments are closed for this article.