2010-04-26 41 views

回答

1

总的来说,我已经受够了RMagick这样的运气不佳,我通常发现很容易只是做一个系统()的命令调用它来修改图像。如果你采取了这种方法,你可以使用你引用的链接中的命令。

9

包括Rmagick。请务必将这些包含在类声明中。

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

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]