如何调整图像的削减它在Python多余的面积? [英] How to resize an image an cut the excess area of it in Python?
问题描述
我有一个包含图像的BASE64 code的字符串。我需要调整此图片591x608px,但我不希望它被变形,如果有不同的比例。
I have a string which contains the base64 code of an image. I need to resize this image to 591x608px, but I don't want it to be deformed if it has a different scale.
我不知道这是不是最好的方式(请纠正我,如果有一个更好的),但我想通过PIL库591x608px的矩形添加到图像。
I don't know if this is the best way (please, correct me if there is a better one), but I'm trying to add a rectangle of 591x608px to the image through the PIL library.
我试图用一个图像文件要做到这一点,它的工作,所以我试图重复这个过程用一个base64字符串,而不是文件的名称。但我并没有达到我的目的。
I tried to do this with an image file and it worked, so I was trying to repeat the process with a base64 string instead of the name of the file. But I didn't achieve my purpose.
from cStringIO import StringIO
from PIL import Image, ImageOps, ImageDraw
size = (591, 608)
mask = Image.new('L', size, 0)
draw = ImageDraw.Draw(mask)
draw.rectangle((0, 0) + size, fill=255)
# From base64 to PIL
image_string = StringIO(my_image.decode('base64'))
im = Image.open(image_string)
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)
# From PIL to base64?
output = base64.b64encode(output)
这是我的许多失败的尝试之一。它给了我一个错误:
This is one of my many failed attempts. It gives me an error:
output = base64.b64encode(output)
TypeError: must be string or buffer, not instance
谁能帮我,好吗?
Can anyone help me, please?
推荐答案
最后,我找到了解决办法。
Finally, I found a solution.
这实际上不是增加一个透明区域(所以我会编辑问题的标题),但它调整图像到指定的规模切割图像的超出部分,如果需要的话:
This isn't actually adding a transparent area (so I'll edit the title of the question), but it's resizing the image to the specified scale cutting the excess part of the image if necessary:
from cStringIO import StringIO
from PIL import Image, ImageOps, ImageDraw
size = (591, 608)
mask = Image.new('L', size, 0)
draw = ImageDraw.Draw(mask)
draw.rectangle((0, 0) + size, fill=255)
# From base64 to PIL
image_string = StringIO(my_image.decode('base64'))
im = Image.open(image_string)
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)
# From PIL to base64
output2 = StringIO()
output.save(output2, format='PNG')
im_data = output2.getvalue()
im_data = im_data.encode('base64')
# data_url = 'data:image/png;base64,' + im_data.encode('base64')
请注意,如果您打印的 im_data em>的,你会看到奇怪的符号(在我的情况,我把这个字符串到一个URL和工程)。如果你想看到的 im_data em>的无符号怪异,取消的最后一行。
Note that if you print im_data, you'll see weird symbols (in my case, I send this string to an URL and works). If you want to see the im_data without weird symbols, uncomment the last line.
这篇关于如何调整图像的削减它在Python多余的面积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!