我有一个rails 4 app,我允许用户上传图片。我有最小尺寸为640X385的验证,因此最小纵横比为1.6623376623376624。现在这意味着用户无法在尺寸或宽高比方面上传较小的图像。当他们上传更大的图像时,它会通过ImageMagick的resize_to_fit方法调整大小。但它调整到比例宽度和高度,我的尺寸验证失败。如果我使用resize_to_fill,即使较小的图像也会被拉伸并绕过纵横比验证。那么如何让调整大小的方法将图像完美地调整为640X385尺寸?
答案 0 :(得分:0)
因此,我不确切地知道您对各种尺寸的期望结果。我倾向于在命令行上使用ImageMagick,所以我制作了一个小脚本,其中包含可能会或可能不会帮助您的示例:
#!/bin/bash
# cleanup
rm *.jpg
# as expected
convert -size 640x385 xc:white img0.jpg
# bigger aspect ratio (2.0)
convert -size 800x400 xc:white img1.jpg
# lower aspect ratio (1.0)
convert -size 800x800 xc:white img2.jpg
# bigger aspect ratio (2.0) but to small
convert -size 400x200 xc:white img3.jpg
# lower aspect ratio (1.0) but to small
convert -size 200x200 xc:white img4.jpg
for img in img*; do
# resize images to fit in box but keep aspect ratio
convert ${img} -resize 640x385 r1.${img}
# resize images keeping the aspectratio to fit in box. But only shrink
# images, images that are to small is not enlarged.
convert ${img} -resize 640x385\> r2.${img}
# resize images ignoring the aspectratio to fit in box. But only shrink
# images, images that are to small is not enlarged.
convert ${img} -resize 640x385\>\! r3.${img}
done
identify -format "%f: %w %h\n" *.jpg
输出如下:
img0.jpg: 640 385
img1.jpg: 800 400
img2.jpg: 800 800
img3.jpg: 400 200
img4.jpg: 200 200
r1.img0.jpg: 640 385
r1.img1.jpg: 640 320
r1.img2.jpg: 385 385
r1.img3.jpg: 640 320
r1.img4.jpg: 385 385
r2.img0.jpg: 640 385
r2.img1.jpg: 640 320
r2.img2.jpg: 385 385
r2.img3.jpg: 400 200
r2.img4.jpg: 200 200
r3.img0.jpg: 640 385
r3.img1.jpg: 640 385
r3.img2.jpg: 640 385
r3.img3.jpg: 400 200
r3.img4.jpg: 200 200
我的猜测是,您正在寻找输出名为r3.<something>
的最后一个变体。
有关如何使用调整大小的更多信息和良好示例:http://www.imagemagick.org/Usage/resize/
另外看看: Resizing the image with padding using convert on ubuntu
我希望这会有所帮助。