Python为图像添加额外区域 [英] Python adding extra area to image
问题描述
所以我有一张图片大小的表格。有像7(66x66,400x400等)
我有一个图像的例子,原始的,总是有600x532的大小。
这个原版可以是电视,PC,...一些产品。
现在我必须调整此图像的大小。那没问题。但如果我按比例做,我会得到类似的东西:66x55。如果我不做比例,图像看起来不太好。
So I have a table with image sizes. There are like 7 (66x66, 400x400, etc.) And I have one example of image, the original, that always has a size of 600x532. On this original can be a TV, a PC, ... some products. Now I have to resize this image. It is no problem. But if I do with proportion I get something like: 66x55. If i dont do with proportion the image doesnt look good.
因此原始背景总是白色。有没有办法扩展图像的区域,并用白色填充其余部分?
所以像这样:600x532 - > 600x600 - > 66x66等等。
So the background of the original is always white. Is there a way to extend the area of the image and filling the rest with white? So like this: 600x532 -> 600x600 -> 66x66 etc etc.
它应该像反作物。
编辑:我发现如果我使用PIL中的crop()而不是使用高于实际图像大小的值最小化它会创建我的额外区域。但它会变成黑色。
我知道如何填补这个区域的白色吗?
I found out that if I use crop() from PIL and instead of "minimizing" using a value above the actual image-size it creates my extra area. but it is going to be black. Any idea how I could fill this area white?
EDIT2:我想这与ImageDraw有关。
I guess it has something to do with ImageDraw.
EDIT3:在发现ImageDraw是解决方案之后,我的问题就解决了。请关闭此。
After finding out that ImageDraw was the solution, my problem was solved. Please close this.
这里我的解决方案:
import Image, ImageDraw
img1 = Image.open("img.jpg")
img2 = img1.crop((0,0,600,600))
draw = ImageDraw.Draw(img2)
draw.rectangle( (0,532,600,600), fill='white' )
del draw
img2.save("img2.jpg","JPEG", quality=75)
接下来我要做的就是让额外的作物上下。所以图片保持在中间位置。
The next thing I will do is to make the extra crop above and under. So the picture stays in the middle.
EDIT4:最终解决方案
final solution
img1 = Image.open("img1.jpg")
img2 = img1.crop( (0,-34,600,566) )
draw = ImageDraw.Draw(img2)
draw.rectangle( (0,0,600,34), fill="white" )
draw.rectangle( (0,566,600,600), fill="white" )
del draw
img2.save("img2.jpg", "JPEG", quality=75)
推荐答案
假设我们使用PIL来处理图像
Supposing we use PIL to process the image
from PIL import Image
def white_bg_square(img):
"return a white-background-color image having the img in exact center"
size = (max(img.size),)*2
layer = Image.new('RGB', size, (255,255,255))
layer.paste(img, tuple(map(lambda x:(x[0]-x[1])/2, zip(size, img.size))))
return layer
您可以调整PIL图像对象的大小,例如img
You could resize a PIL Image object, img for example
img.resize((width, height), resample=Image.ANTIALIAS)
因此在python shell中,它看起来像
Thus in the python shell, it looks like
>>> from PIL import Image
>>> img = Image.open('path/to/image')
>>> square_one = white_bg_square(img)
>>> square_one.resize((100, 100), Image.ANTIALIAS)
>>> square_one.save('path/to/result')
在PIL文档和sorl中有很好的例子-thumbnail 3.2.5
There are nice examples inside PIL document and sorl-thumbnail 3.2.5
- http://effbot.org/imagingbook/image.htm
- http://pypi.python.org/pypi/sorl-thumbnail/3.2.5
这篇关于Python为图像添加额外区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!