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?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With