2011-01-13 148 views
2

我想調整大小/縮放圖像。原件的尺寸與300x200或512x600不一樣。我想將圖像大小調整爲100x100,但不要從圖像或更改比例中剪裁任何圖像。理想情況下,圖像首先將長邊縮放到100(寬高比),然後用白色填充較小的邊緣。RMagick:爲縮略圖縮放和調整圖像大小

.---------. 
|- - - - -| 
| IMAGE | 
|- - - - -| 
'---------' 

我不使用Paperclip或Rails,只是RMagick。

回答

5

我已經完成了與一個新的100x100圖像合併大小調整後的圖像。那肯定不是最好的方式,但它的工作原理:

img = Magick::Image.read("file.png").first 
target = Magick::Image.new(100, 100) do 
    self.background_color = 'white' 
end 
img.resize_to_fit!(100, 100) 
target.composite(img, Magick::CenterGravity, Magick::CopyCompositeOp).write("file-small.png) 
1

與它玩了一會兒我Fu86的複合伎倆,像這樣的工作後:

img = Image.read("some_file").first().resize_to_fit!(width, height) 
target = Image.new(width, height) do 
    self.background_color = 'white' 
end 
target.composite(img, CenterGravity, AtopCompositeOp).write("some_new_file") 

AtopCompositeOp似乎比CopyCompositeOp,它變成了黑色由於某種原因,我的背景的一部分,以更好地工作。

1
image = Magick::Image.read("filename").first 
resized = image.resize_to_fit(width, height)  # will maintain aspect ratio, so one of the resized dimensions may be less than the specified dimensions 
resized.background_color = "#FFFFFF"    # without a default, background color will vary based on the border of your original image 
x = (resized.columns - width)/2    # calculate necessary translation to center image on background 
y = (resized.rows - height)/2 
resized = resized.extent(width, height, x, y) # 'extent' fills out the resized image if necessary, with the background color, to match the full requested dimensions. the x and y parameters calculated in the previous step center the image on the background. 
resized.write("new_filename") 

注:在Heroku,這是此張貼使用的ImageMagick 6.5.7-8,我需要乘以-1 x和y的轉換(和發送正數)。版本6.8.0-10期望負數。