views:

36

answers:

2

I'm trying to set up a python script in cgi-bin that simply returns a header with content-type: image/png and returns the image. I've tried opening the image and returning it with print f.read() but that isn't working.

EDIT: the code I'm trying to use is:

print "Content-type: image/png\n\n"
with open("/home/user/tmp/image.png", "r") as f:
    print f.read()

This is using apache on ubuntu server 10.04. When I load the page in chrome I get the broken image image, and when I load the page in firefox I get The image http://localhost/cgi-bin/test.py" cannot be displayed, because it contains errors.

+2  A: 
  1. You may need to open the file as "rb" (in windows based environments it's usually the case.
  2. Simply printing may not work (as it adds '\n' and stuff), better just write it to sys.stdout.
  3. The statement print "Content-type: image/png\n\n" actually prints 3 newlines (as print automatically adds one "\n" in the end. This may brake your PNG file.

Try:

sys.stdout.write( "Content-type: image/png\n\n" + file(filename,"rb").read() )
adamk
Unfortunately this isn't working - same thing.
iboeno
Yup, #3 was it. Thanks for following up.
iboeno
A: 

Are you including the blank line after the header? If not, it's not the end of your headers!

print 'Content-type: image/png'
print
print f.read()

bowenl2