需要一种简单的方法来圆角化图像。我需要边角是透明的。这个链接展示了如何通过命令行实现:
http://www.imagemagick.org/Usage/thumbnails/#rounded
我需要对应的RMagick\Ruby代码...谢谢!
http://www.imagemagick.org/Usage/thumbnails/#rounded
我需要对应的RMagick\Ruby代码...谢谢!
在你的源代码中包含 Rmagick。确保将 include 放在类声明内部。
require 'rmagick'
include Magick
创建一个方法,就像这样。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
像这样调用该方法
source_image = Image.read('my-big-image.jpg').first
thumbnail_image = thumb(source_image, '64x64>', 8)
thumbnail_image.write('thumb.png')
我这样结构的原因是在创建缩略图时,我已经打开了图片以进行其他用途。对于你来说,将文件操作直接放在方法中可能更合理。使用Fitter Man的代码与CarrierWave::RMagick
结合使用
方法:
def resize_and_round(geometry_string, radius = 10)
manipulate! do |original|
original.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 = Magick::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.
Magick::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, 4,4, Magick::CopyOpacityCompositeOp)
thumb
end
end
end
使用方法:
process :resize_and_round => ['200x200', 20]
一般来说,我对RMagick的运气非常不好,所以我通常发现只需在系统调用中使用命令来修改图像更容易。如果您采用这种方法,您可以使用您提到的链接中的完全相同的命令。
http://dmathieu.com/articles/development/create-your-own-carrierwave-processors/