V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
aiqier
V2EX  ›  Python

flask 如何返回图片流

  •  
  •   aiqier · 2015-11-27 10:40:26 +08:00 · 6543 次点击
    这是一个创建于 3044 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我的 flask 需要通过传入的 url 参数,通过 qrcode 库生成二维码图片,然后将它写入流中返回。

    import qrcode
    qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    box_size=10,
    border=1
    )
    qr.add_data(url)
    img = qr.make_image()
    生成的 qrcode.image.pil.PilImage 对象并没有太多的方法可用,

    但可以通过: img.convert("RGBA ”)能得到一个 PIL.Image.Image 对象
    我想请教:
    1.如何把这个 Image 对象,通过流读出来。
    2.如何把这个流通过 flask 写给请求者。

    3 条回复    2015-11-27 15:53:52 +08:00
    thomaspaine
        1
    thomaspaine  
       2015-11-27 10:58:24 +08:00   ❤️ 1
    img = qr.make_image()
    buf = StringIO.StringIO()
    img.save(buf, 'jpeg')
    buf_str = buf.getvalue()
    response = app.make_response(buf_str)
    response.headers['Content-Type'] = 'image/jpeg'
    return response
    从 qr.make_image()接下去,我是这么写的,供参考
    knightdf
        2
    knightdf  
       2015-11-27 11:28:33 +08:00
    返回图片数据就好了,图片也是数据流,把数据解析成图片那是显示的时候的事
    ryd994
        3
    ryd994  
       2015-11-27 15:53:52 +08:00 via Android
    你可以返回一个 iterator
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   981 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:18 · PVG 04:18 · LAX 13:18 · JFK 16:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.