Stack Overflow Asked by user504909 on March 1, 2021
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.
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)
# ...
Correct answer by v25 on March 1, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP