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

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

问题描述

我在我的应用程序中使用了烧瓶.我想将图像(由 PIL 动态生成)发送到客户端而不保存在磁盘上.

I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk.

知道怎么做吗?

推荐答案

首先,您可以将图像保存到 tempfile 并删除本地文件(如果有):

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)

其次,将临时文件设置为响应(根据 这个 stackoverflow 问题):

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天全站免登陆