【问题标题】:flask return pil generate image error, I can see the resize pictures but the response image is errorflask return pil 生成图像错误,我可以看到调整大小的图片但响应图像是错误的
【发布时间】:2021-01-05 16:43:34
【问题描述】:

我有flask api响应图片:

FORMAT = {'image/jpeg':'JPEG', 'image/bmp':'BMP', 'image/png':'PNG', 'image/gif': 'GIF'}

@app.route('/api/image/<id>/<str_size>', methods=['get'])
def show_thumbnail(id, str_size):
    size = int(str_size)
    with get_db().cursor() as cur:
        cur.callproc('getimage', (id,))
        result = cur.fetchone()
        buf = BytesIO(result[1])
        if(size>0):
            im = Image.open(buf)
            im.thumbnail((size, size))
            buf = BytesIO(b'')
            im.save(buf, format=FORMAT[result[0].lower()])
        fw = open('w03.jpg', 'wb')
        fw.write(buf.getbuffer())
        fw.close()
        resp = Response(buf)
        resp.headers.set('Content-Type', result[0].lower())
    return resp

ps:

结果[0] = '图像/jpeg'

result[1]是jpeg图片的字节数组。

如果我设置 size(str_size) = 0,我的意思是我不运行 PIL Image 缩略图代码部分。我可以得到正确的图片作为回应。

例如,如果我设置 size(str_size) = 256,我发现 'w03.jpg' 是正确的,我可以得到正确的调整大小图像,但响应是黑色的,原因是图像包含错误。

【问题讨论】:

  • 如果result[0]image/jpeg,则不能将其传递给im.save()format 参数。那应该是jpg,而不是image/jpeg
  • @Mark Setchell 我直接给出格式。如果 im.save() 没有格式,它取决于扩展名。如果给出格式,则取决于格式我直接使用FORMAT字典给出格式'JPEG'。

标签: image flask file-io python-imaging-library


【解决方案1】:

im.save(buf) 将缓冲区放到最后。您需要在构建 resp 之前将其倒带使用 buf.seek(0) 执行此操作。我怀疑 buf.getbuffer 没有以同样的方式改变流位置,这可以解释为什么w03.jpg 在第二个测试中是正确的:

您还可以使用with 块来最小化一些代码(这会自动关闭文件):

        # ...
        with open('w03.jpg', 'wb') as fw:
            fw.write(buf.getbuffer())

        buf.seek(0)
        resp = Response(buf)
        # ...

【讨论】:

    猜你喜欢
    • 2016-11-06
    • 2020-10-12
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2014-01-25
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多