Adding rounded corners with RMagick

Posted by Jocelyn Sat, 22 Sep 2007 20:21:00 GMT

I recently had to dynamically add rounded corners to uploaded images in a Rails application.

While a quick search lead me to a few online tutorials, they really were too complex for what I had in mind.

So here is what will give you nice rounded corners with white background (no transparency), easily.

You will need RMagick, a Ruby library based on ImageMagick and GraphicsMagick that offers great image manipulation and drawing funtions.

require 'RMagick'
include Magick

# will return the new image
def rounded_corners(image)
  width = image.columns
  height = image.rows
  # create a masq of same size
  masq = Image.new(width, height)
  d = Draw.new
  # 10 is the corner's radius
  d.roundrectangle(0, 0, width - 1, height - 1, 10, 10)
  d.draw(masq)
  image.composite(masq, 0, 0, LightenCompositeOp)
end

How does it work? Well, we simply create an image with a black rounded-corner rectangle on white background. Then we use composite with Lighten. This will increase brightness in the source image, the black rectangle having no effect, while the white corners will force white in the resulting image.

And... that's it. Easy enough I guess. I did not bother messing around with transparency since the JPEG format does not support it anyway.

Posted in  | no comments