2010-04-26 43 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]