将二进制文件转换为Google App Engine中的PIL图像数据类型 [英] Converting binary file into PIL Image datatype in Google App Engine
问题描述
我使用Google App Engine与Python和Jinja作为模板。在我的HTML模板中,我有这段代码,它允许用户选择一个文件(Image):
< form action =/ step2enctype =multipart / form-datamethod =post>
< input type =filename =datafilesize =40>
< input type =submitvalue =upload>
< / form>
在发布后,我可以通过self.request.get('datafile')获取图片,这似乎是一种二进制数据类型('str')。我把它放到数据库中,我可以显示这个:
self.response.out.write('< div> ;< img src =img?img_id =%s>< / img>'%userimages.key())
我正在努力找到一种方法将其转换为PIL.Image数据类型,以便使用它进行图像处理。提前致谢!
将字符串放入 StringIO
对象中:
from cStringIO import StringIO
imgfile = StringIO(self.request.get('datafile')) )
img = Image.open(imgfile)
所有PIL需求都是类似文件目的; StringIO
为给出的字符串提供实际的数据。
另一方面, PIL
写入 StringIO
对象,但您需要指定使用的格式:
imgfile = StringIO()
img.save(imgfile,format ='PNG')
imagestring = imgfile.getvalue()
I am using Google App Engine with Python and Jinja for the templates. In my HTML template, I have this piece of code, which allows the user to choose a file (Image):
<form action="/step2" enctype="multipart/form-data" method="post">
<input type="file" name="datafile" size="40">
<input type="submit" value="upload" >
</form>
Upon post, I am able to get the image via self.request.get('datafile'), and this appears to be a binary data type ('str'). I put this into a database, and I can display this with:
self.response.out.write('<div><img src="img?img_id=%s"></img>' % userimages.key())
I am struggling to find a way to convert this into a PIL.Image data type, in order to do image processing with it. Thanks in advance!
Put the string in a StringIO
object:
from cStringIO import StringIO
imgfile = StringIO(self.request.get('datafile'))
img = Image.open(imgfile)
All PIL needs is a file-like object; StringIO
provides this source the actual data from the given string.
In the other direction, have PIL
write to a StringIO
object, but you do need to specify the format used:
imgfile = StringIO()
img.save(imgfile, format='PNG')
imagestring = imgfile.getvalue()
这篇关于将二进制文件转换为Google App Engine中的PIL图像数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!