Search code examples
rubyimage-processingimagemagickrmagick

Cut circle out of image with RMagick


I want to cut a circle out of an image using rmagick.

Here's an example of what I'd like to be able to accomplish:

http://img375.imageshack.us/img375/1153/walterf.jpg --> http://img15.imageshack.us/img15/8129/circlethumb.png

It seems like I want to use http://studio.imagemagick.org/RMagick/doc/draw.html#circle to cut a circle, and then clip_path to mask it, but the docs aren't very clear. Would anyone be able to point me in the right direction?


Solution

  • require 'rmagick'
    
    im = Magick::Image.read('walter.jpg').first
    
    circle = Magick::Image.new 200, 200
    gc = Magick::Draw.new
    gc.fill 'black'
    gc.circle 100, 100, 100, 1
    gc.draw circle
    
    mask = circle.blur_image(0,1).negate
    
    mask.matte = false
    im.matte = true
    im.composite!(mask, Magick::CenterGravity, Magick::CopyOpacityCompositeOp)
    
    im.write 'walter_circle.png'