从 POST 解码 base64 以在 PIL 中使用 [英] Decoding base64 from POST to use in PIL
问题描述
我正在 Flask 中创建一个简单的 API,它接受以 base64 编码的图像,然后使用 Pillow 对其进行解码以进行进一步处理.
我查看了一些示例(1、2、3),我想我明白了这个过程的要点,但我不断收到一个错误,枕头无法读取我给的字符串.
这是我到目前为止所得到的:
import cStringIO从 PIL 导入图像导入 base64数据 = request.formimage_string = cStringIO.StringIO(base64.b64decode(data['img']))图像 = Image.open(image_string)
给出错误:
IOError: cannot identify image file
您应该尝试以下操作:
from PIL 导入图片从 io 导入 BytesIO导入 base64data['img'] = '''R0lGODlhDwAPAKECAAAAzMzM////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='''im = Image.open(BytesIO(base64.b64decode(data['img'])))
您的 data['img']
字符串不应包含示例 JSFiddle 中的 HTML 标记或参数 data:image/jpeg;base64
.>
为了便于阅读,我更改了从 Google 获取的示例的图像字符串.
I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.
I've looked at some examples (1, 2, 3), and I think I get the gist of the process, but I keep getting an error where Pillow can't read the string I gave it.
Here's what I've got so far:
import cStringIO
from PIL import Image
import base64
data = request.form
image_string = cStringIO.StringIO(base64.b64decode(data['img']))
image = Image.open(image_string)
which gives the error:
IOError: cannot identify image file <cStringIO.StringIO object at 0x10f84c7a0>
You should try something like:
from PIL import Image
from io import BytesIO
import base64
data['img'] = '''R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLl
N48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=='''
im = Image.open(BytesIO(base64.b64decode(data['img'])))
Your data['img']
string should not include the HTML tags or the parameters data:image/jpeg;base64
that are in the example JSFiddle.
I've changed the image string for an example I took from Google just for readability purposes.
这篇关于从 POST 解码 base64 以在 PIL 中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!