使用RMagick从图像中裁剪圆形

6
我想使用rmagick从图像中裁剪出一个圆形。 以下是我想要实现的示例: http://img375.imageshack.us/img375/1153/walterf.jpg --> http://img15.imageshack.us/img15/8129/circlethumb.png 看起来我需要使用http://studio.imagemagick.org/RMagick/doc/draw.html#circle来切割一个圆形,然后使用clip_path进行遮罩处理,但文档不是很清楚。有人能指点我正确的方向吗?
2个回答

12
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'

你如何使用两张图片来完成这个任务?不使用圆形,而是使用一个透明的图片。 - John Pollard
这个解决方案不适用于带有 alpha 通道的 png 图像。 - Dmitriy

1
这是我使用Imagemagick和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");

你应该能够跟随这个过程吧?

清理临时图像 - 我倾向于将临时图像保存为 .miff 格式,然后编写一个循环来删除所有 .miff 图像。或者,只需将它们保留下来,如果您对临时图像使用相同的名称,则每次运行代码时都会被覆盖。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接