推荐学习书目
› 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 · Nov 27, 2015 · 7524 views
    This topic created in 3955 days ago, the information mentioned may be changed or developed.

    我的 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 replies  •  2015-11-27 15:53:52 +08:00
    thomaspaine
        1
    thomaspaine  
       Nov 27, 2015   ❤️ 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  
       Nov 27, 2015
    返回图片数据就好了,图片也是数据流,把数据解析成图片那是显示的时候的事
    ryd994
        3
    ryd994  
       Nov 27, 2015 via Android
    你可以返回一个 iterator
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2469 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 06:06 · PVG 14:06 · LAX 23:06 · JFK 02:06
    ♥ Do have faith in what you're doing.