Python 从 POST 解码 base64 以在 PIL 中使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26070547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Decoding base64 from POST to use in PIL
提问by Lazaro Gamio
I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.
我正在 Flask 中制作一个简单的 API,它接受以 base64 编码的图像,然后使用 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.
我看过一些例子(1、2、3),我想我明白了这个过程的要点,但我一直收到一个错误,枕头无法读取我给它的字符串。
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>
采纳答案by André Teixeira
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)))
Your data['img']string should not include the HTML tags or the parameters data:image/jpeg;base64that are in the example JSFiddle.
您的data['img']字符串不应包含data:image/jpeg;base64示例 JSFiddle 中的 HTML 标记或参数。
I've changed the image string for an example I took from Google just for readability purposes.
出于可读性目的,我更改了从 Google 获取的示例的图像字符串。
回答by mhawke
There is a metadata prefix of data:image/jpeg;base64,being included in the imgfield. Normally this metadata is used in a CSS or HTML data URI when embedding image data into the document or stylesheet. It is there to provide the MIME type and encoding of the embedded data to the rendering browser.
字段data:image/jpeg;base64,中包含一个元数据前缀img。通常,在将图像数据嵌入文档或样式表时,此元数据用于 CSS 或 HTML 数据 URI。它用于向渲染浏览器提供嵌入数据的 MIME 类型和编码。
You can strip off the prefix before the base64 decode and this should result in valid image data that PIL can load (see below), but you really need to question how the metadata is being submitted to your server as normally it should not.
您可以在 base64 解码之前去除前缀,这应该会导致 PIL 可以加载的有效图像数据(见下文),但您确实需要质疑元数据是如何提交到您的服务器的,因为通常不应该这样做。
import re
import cStringIO
from PIL import Image
image_data = re.sub('^data:image/.+;base64,', '', data['img']).decode('base64')
image = Image.open(cStringIO.StringIO(image_data))
回答by cyberj0g
Sorry for necromancy, but none of the answers worked completely for me. Here is code working on Python 3.6 and Flask 0.13.
抱歉死灵法术,但没有一个答案完全适合我。这是在 Python 3.6 和 Flask 0.13 上运行的代码。
Server:
服务器:
from flask import Flask, jsonify, request
from io import BytesIO
from web import app
import base64
import re
import json
from PIL import Image
@app.route('/process_image', methods=['post'])
def process_image():
image_data = re.sub('^data:image/.+;base64,', '', request.form['data'])
im = Image.open(BytesIO(base64.b64decode(image_data)))
return json.dumps({'result': 'success'}), 200, {'ContentType': 'application/json'}
Client JS:
客户端JS:
// file comes from file input
var reader = new FileReader();
reader.onloadend = function () {
var fileName = file.name;
$.post('/process_image', { data: reader.result, name: fileName });
};
reader.readAsDataURL(file);

