4

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.

iboeno
  • 3,809
  • 4
  • 20
  • 13
  • 2
    If you post the code, you will get better responses. Also, if you could describe what is happening, rather than just "that isn't working", we'll have more clues to work from. – Ned Batchelder Jul 07 '10 at 19:26

2 Answers2

7
  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 break your PNG file.

Try:

sys.stdout.write( "Content-type: image/png\r\n\r\n" + file(filename,"rb").read() )
  1. HTML responses require carriage-return, new-line
adamk
  • 45,184
  • 7
  • 50
  • 57
  • 1
    Yup, #3 was it. Thanks for following up. – iboeno Jul 07 '10 at 19:49
  • @adamk if i want to execute something from the script and then do it , it is not working from me. Suppose i want to create a file and then close it. it returns the image but the file does not get created on server. Any inputs ? #!/usr/bin/env python import sys f = open('workfile', 'w') f.close() filename="th_goldhill.png" sys.stdout.write( "Content-type: image/png\r\n\r\n" + file(filename,"rb").read() ) – Peter May 28 '13 at 15:14
0

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()

Hut8
  • 6,080
  • 4
  • 42
  • 59
  • 1
    how will be sure `all string characters reading correctly ? ` . I try this method million time but haven't any success. Did you have any idea about `print` function ? Where moderator ? Don't waste users lives ! -1 – dsgdfg Jul 22 '16 at 06:51