如何将PIL生成的图像发送给浏览器? [英] How to send image generated by PIL to browser?

查看:157
本文介绍了如何将PIL生成的图像发送给浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用我的应用程序的烧瓶。我想发送一个图像(由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

@ app.route('stackoverflow question
):
/ path')
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屋!

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