How to resize an image an cut the excess area of it in Python?

折月煮酒 提交于 2019-12-11 06:53:31

问题


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.

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.

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?


回答1:


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')

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.



来源:https://stackoverflow.com/questions/28459661/how-to-resize-an-image-an-cut-the-excess-area-of-it-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!