Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
switz Avatar asked Jun 27 '12 19:06

switz


2 Answers

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'
like image 182
Faridco Avatar answered Sep 19 '22 21:09

Faridco


This is how I would do it with Imagemagick and php:

// Canvas the same size as the final image
exec("convert -size 800x533 xc:white white.jpg");
// The mask 
exec("convert -size 800x533 xc:none -draw \"fill black circle 400,265 400,50\"  write_mask.png");
// Cut the whole out of the canvas  
exec("composite -compose Dst_Out write_mask.png white.jpg -matte step.png");
// Put the canvas over the image and trim off excess white background   
exec("convert IMG_5745.jpg  step.png -composite -trim final.jpg");

You should be able to follow the process?

Cleanup tempory images afterwards - I tend to save the tempory images in a .miff format and then write a loop to delete all .miff images afterwards. Alternativly just leave them and if you use the same name for the tempory images they will be overwritten every time the code is run.

like image 29
Bonzo Avatar answered Sep 19 '22 21:09

Bonzo