Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending image to webpage - how to change Python 2 code to Python 3?

For many years I have used a small Python2 script which sends thumbnails of images to a webpage.

A minimal working version is:

Webpage:

<img src="./sendthumb.cgi" />

Python2 script sendthumb.cgi:

#! /usr/bin/python

from PIL import Image
from StringIO import StringIO
import sys

pic = "testpic.jpg"

im = Image.open(pic)
im.thumbnail((256, 256))
buf = StringIO()
im.save(buf, "JPEG")

sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/jpeg\r\n')
sys.stdout.write('\r\n')
sys.stdout.write(buf.getvalue())

However, my service providers are now switching off Python2, so it's time to amend the script to work with Python3. A bit of research suggests that I need to switch StringIO to BytesIO, and send to sys.stdout.buffer. So the new script is:

#! /usr/bin/python3

from PIL import Image
from io import BytesIO
import sys

pic = "testpic.jpg"

im = Image.open(pic)
im.thumbnail((256, 256))
buf = BytesIO()
im.save(buf, "JPEG")

sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/jpeg\r\n')
sys.stdout.write('\r\n')
sys.stdout.buffer.write(buf.getvalue())

This doesn't seem to trigger any errors - but it also doesn't display the image on the webpage. Could somebody point out how to correct this?

like image 340
Andy31 Avatar asked Jan 19 '26 08:01

Andy31


1 Answers

To answer my own question, in case it helps others.

The solution is to send all the output to sys.stdout.buffer:

sys.stdout.buffer.write(b'Status: 200 OK\r\n')
sys.stdout.buffer.write(b'Content-type: image/jpeg\r\n')
sys.stdout.buffer.write(b'\r\n')
sys.stdout.buffer.write(buf.getvalue())
like image 86
Andy31 Avatar answered Jan 20 '26 23:01

Andy31