3

I'm trying to load an image file from my local disk and output it over http when the script is accessed on my webserver via cgi.

For example I want http://example.com/getimage.py?imageid=foo to return the corresponding image. Just opening the file and printing imgfile.read() after the appropriate content headers, however, causes the image to be scrambled. Clearly the output isn't right, but I have no idea why.

What would be the best way to do this, using the built-in modules of 2.6?

Edit:

The code essentially boils down to:

imgFile=open(fileName,"rb")
print "Content-type: image/jpeg"
print
print imgFile.read()
imgFile.close()

It outputs an image, just one that seems to be random data.

Kal Zekdor
  • 1,172
  • 2
  • 13
  • 23

2 Answers2

3

You probably have to open() your image files in binary mode:

imgfile = open("%s.png" % imageid, "rb")
print imgfile.read()

On Windows, you need to explicitly make stdout binary:

import sys
if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

You also might want to use CR+LF pairs between headers (see RFC 2616 section 6):

imgFile = open(fileName, "rb")
sys.stdout.write("Content-type: image/jpeg\r\n")
sys.stdout.write("\r\n")
sys.stdout.write(imgFile.read())
imgFile.close()
Community
  • 1
  • 1
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • No, I did that from the start. Also of note is that I can read the image and write it to another file with no problem, only outputting it causes the issue. – Kal Zekdor Nov 14 '10 at 08:30
  • @Kal, I see. Does that work better if you call `sys.stdout.write()` instead of `print`? Are you running Windows? – Frédéric Hamidi Nov 14 '10 at 08:50
  • @Kal, if you're running Windows, there are additional [hoops](http://stackoverflow.com/questions/2374427/python-2-x-write-binary-output-to-stdout) to jump through, but if you're on Linux that should work fine as it is. – Frédéric Hamidi Nov 14 '10 at 08:58
  • On windows, yes, using IIS 7. – Kal Zekdor Nov 14 '10 at 09:06
0

Python comes with its own HTTP module, SimpleHTTPServer - why not check out SimpleHTTPServer.py in the /Lib directory of your Python installation, and see how it is done there?

PaulMcG
  • 62,419
  • 16
  • 94
  • 130