Thursday, July 15, 2010

python plumbing: PIL Image from data string

Today I wanted to use netcat (nc) to send a JPEG image file over a network to a python script so that I can manipulate it with PIL, the python imaging library.

PIL has fromstring and frombuffer methods, but I couldn't get them to work. But I found the ImageFile module, which let me feed the data in as it came off the socket.

To serve up the images, I did this from the shell:

while true ; do nc -q 0 -l -p 12345 < foo.jpg ; done


Then this python script received and displayed an image:

#!/usr/bin/python

import socket
from PIL import ImageFile

tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.connect(('127.0.0.1', 12345))
tcp.send("1000 4")

file = open("bar.jpg", "w")
parser = ImageFile.Parser()

while 1:
jpgdata = tcp.recv(65536)
if not jpgdata:
tcp.close()
break

parser.feed(jpgdata)
file.write(jpgdata)

file.close()
image = parser.close()
image.show()

1 comment:

Unknown said...

Thank you very match