1
我有一個字符串,其中包含圖像的base64代碼。我需要將此圖像調整爲591x608px,但如果它具有不同的比例,我不希望它變形。如何調整圖像的大小並在Python中剪切多餘的區域?
我不知道這是否是最好的方法(請更正我,如果有更好的方法),但我試圖通過PIL庫向圖像添加一個矩形591x608px。
我試圖用圖像文件做到這一點,它的工作原理,所以我試圖用base64字符串而不是文件的名稱重複該過程。但是我沒有達到我的目的。
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)
這是我的許多失敗嘗試之一。它給我一個錯誤:
output = base64.b64encode(output)
TypeError: must be string or buffer, not instance
任何人都可以幫助我嗎?