Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

flask return pil generate image error, I can see the resize pictures but the response image is error

I have flask api response picture:

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:

result[0] = 'image/jpeg'

result[1] is the bytes array of jpeg picture.

If I set the size(str_size) = 0, I mean I do not run PIL Image thumbnail code part. I can get the correct picture in response.

If I set the size(str_size) = 256 for instance, I find the 'w03.jpg' is correct and I can get the correct resize image, but the response is black for the reason is the image contains error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

im.save(buf) puts the buffer to the end. You need to rewind this before building resp Do this with buf.seek(0). I suspect buf.getbuffer doesn't change the stream position in the same way, which would explain why w03.jpg is correct in the second test:

You can also use a with block to minimize some of the code (this auto closes the file):

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...