Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RMagick Rounded Corners

Need a simple a way of rounding off an Image. I need the corners to be transparent. This link shows how to do it via command line:

http://www.imagemagick.org/Usage/thumbnails/#rounded

What I need is the corresponding RMagick\Ruby code... Thanks!

like image 473
mikeycgto Avatar asked Apr 26 '10 19:04

mikeycgto


1 Answers

Include Rmagick in your source code. Be sure to place the include inside the class declaration.

require 'rmagick'
include Magick

Create a method, like this

def thumb(source_image, geometry_string, radius = 10)
  source_image.change_geometry(geometry_string) do |cols, rows, img| 

    # Make a resized copy of the image
    thumb = img.resize(cols, rows)

    # Set a transparent background: pixels that are transparent will be
    # discarded from the source image.
    mask = Image.new(cols, rows) {self.background_color = 'transparent'}

    # Create a white rectangle with rounded corners. This will become the
    # mask for the area you want to retain in the original image.
    Draw.new.stroke('none').stroke_width(0).fill('white').
        roundrectangle(0, 0, cols, rows, radius, radius).
        draw(mask)

    # Apply the mask and write it out
    thumb.composite!(mask, 0, 0, Magick::CopyOpacityCompositeOp)
    thumb
  end
end

Call the method like this

source_image = Image.read('my-big-image.jpg').first
thumbnail_image = thumb(source_image, '64x64>', 8)
thumbnail_image.write('thumb.png')

I structured it this way because I already have the image open for another purpose at the point I'm creating the thumbnail. It might make more sense for you to put the file operations right in the method.

Also, you might want to look at how geometry strings work http://www.imagemagick.org/RMagick/doc/imusage.html#geometry

like image 163
Fitter Man Avatar answered Oct 16 '22 06:10

Fitter Man