从POST解码base64以在PIL中使用 [英] Decoding base64 from POST to use in PIL

查看:388
本文介绍了从POST解码base64以在PIL中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Flask中制作了一个简单的API接受以base64编码的图像,然后使用Pillow对其进行解码以便进一步处理。

我已经看过一些示例( 1 2 3 ),我想我得到了这个过程的要点,但是在枕头无法读取我给它的字符串的时候,我总是收到一个错误。



以下是我到目前为止:

  import cStringIO 
从PIL导入Image
导入base64

data = request.form
image_string = cStringIO.StringIO(base64.b64decode(data ['img']))
image = Image.open(image_string)

给出错误:

  IOError:can不识别图像文件< cStringIO.StringIO对象在0x10f84c7a0> 


解决方案

b
$ b



 从IO进口BytesIO 
进口的base64

数据PIL进口图片
[ 'IMG'] = '' 'R0lGODlhDwAPAKECAAAAzMzM ///// wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN​​48CXF8m2iQ3YmmKqVlRtW4MLwWACH + H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw ==' ''

im = Image.open(BytesIO(base64.b64decode(data)))

您的data ['img']字符串不应该包含html标记,或者在示例jsfiddle中的参数 data:image / jpeg; base64,。 b $ b

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:

I will change the image string for an example I took from google just for readability purposes.

from PIL import Image
from io import BytesIO
import base64

data['img'] = '''R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==''' 

im = Image.open(BytesIO(base64.b64decode(data)))

Your data['img'] string should not include the html tags, or the parameters data:image/jpeg;base64, that are in the example jsfiddle.

这篇关于从POST解码base64以在PIL中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆