[Answer]-StringIO problems when trying to create JSON response with image

1👍

The problem is

canvas.print_png(img_buffer)

leaves the file pointer at the end of the “file”, so img_buffer.read() returns an empty string. You could call img_buffer.seek(0) immediately after calling canvas.print_png(img_buffer), but in fact, your out variable is not necessary. Instead, replace this:

base64.encode(img_buffer, out)
img_str = out.getvalue()

with:

img_str = base64.encodestring(img_buffer.getvalue())

Or, since base64.encodestring is part of the legacy interface, it might be better to use:

img_str = base64.b64encode(s.getvalue())

Leave a comment