使用python为图像添加边框 [英] Adding borders to an image using python
问题描述
我有大量固定大小的图像(比如说500 * 500)。我想编写一个python脚本,将其大小调整为固定大小(比如800 * 800),但会将原始图像保持在中心,并用固定颜色(比如黑色)填充多余区域。
I have a large number of images of a fixed size (say 500*500). I want to write a python script which will resize them to a fixed size (say 800*800) but will keep the original image at the center and fill the excess area with a fixed color (say black).
我正在使用PIL。我现在可以使用 resize
函数调整图像大小,但这会改变宽高比。有没有办法做到这一点?
I am using PIL. I can resize the image using the resize
function now, but that changes the aspect ratio. Is there any way to do this?
推荐答案
您可以使用所需的新尺寸创建新图像,并粘贴旧图像在中心,然后保存它。如果你愿意,你可以覆盖原始图像(你确定吗?; o)
You can create a new image with the desired new size, and paste the old image in the center, then saving it. If you want, you can overwrite the original image (are you sure? ;o)
import Image
old_im = Image.open('someimage.jpg')
old_size = old_im.size
new_size = (800, 800)
new_im = Image.new("RGB", new_size) ## luckily, this is already black!
new_im.paste(old_im, ((new_size[0]-old_size[0])/2,
(new_size[1]-old_size[1])/2))
new_im.show()
# new_im.save('someimage.jpg')
这篇关于使用python为图像添加边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!