
Question:
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?
Answer1: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 <em>im_data</em>, you'll see weird symbols (in my case, I send this string to an URL and works). If you want to see the <em>im_data</em> without weird symbols, uncomment the last line.