2011-01-13 123 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期望负数。