如何将PIL生成的图像发送给浏览器? [英] How to send image generated by PIL to browser?
本文介绍了如何将PIL生成的图像发送给浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何想法如何做到这一点?
解决方案
首先,您可以将图像保存到 tempfile 并删除本地文件(如果有的话):
from tempfile导入NamedTemporaryFile $ b $ from shutil import copyfileobj $ b $ from os import remove
tempFileObj = NamedTemporaryFile(mode ='w + b',suffix ='jpg')
pilImage = open('/ tmp / myfile.jpg','rb')
copyfileobj(pilImage,tempFileObj)
pilImage.close()
remove('/ tmp / myfile .jpg')
tempFileObj.seek(0,0)
其次,设置temp文件到响应(按照这
pre $ from flask import send_file
): / path')
@ app.route('stackoverflow question
def view_method():
response = send_file(t empFileObj,as_attachment = True,attachment_filename ='myfile.jpg')
返回响应
I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk.
Any idea how to do this ?
解决方案
First, you can save the image to a tempfile and remove the local file (if you have one):
from tempfile import NamedTemporaryFile
from shutil import copyfileobj
from os import remove
tempFileObj = NamedTemporaryFile(mode='w+b',suffix='jpg')
pilImage = open('/tmp/myfile.jpg','rb')
copyfileobj(pilImage,tempFileObj)
pilImage.close()
remove('/tmp/myfile.jpg')
tempFileObj.seek(0,0)
Second, set the temp file to the response (as per this stackoverflow question):
from flask import send_file
@app.route('/path')
def view_method():
response = send_file(tempFileObj, as_attachment=True, attachment_filename='myfile.jpg')
return response
这篇关于如何将PIL生成的图像发送给浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文