RMagick圆角

5
5个回答

12

在你的源代码中包含 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')
我这样结构的原因是在创建缩略图时,我已经打开了图片以进行其他用途。对于你来说,将文件操作直接放在方法中可能更合理。
此外,您可能需要查看几何字符串的工作方式:http://www.imagemagick.org/RMagick/doc/imusage.html#geometry

2022年1月:我不得不用"Magick::CopyAlphaCompositeOp"替换"Magick::CopyOpacityCompositeOp"。 - Metaphysiker

4

使用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]

3

我之前使用了一个手动编写的图像解决方案,但也许我会转换到Paperclip。谢谢。 - mikeycgto

2

一般来说,我对RMagick的运气非常不好,所以我通常发现只需在系统调用中使用命令来修改图像更容易。如果您采用这种方法,您可以使用您提到的链接中的完全相同的命令。


1

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