Writing an image

M

Mr. Costington

Hi all, I was trying to hava a CGI script return an image, but it was coming
back corrupted. So I tried this simple non-CGI test and still get errors:

import sys
image = open('pic.jpg','rb').read()
sys.stdout.write(image)

When I run this like "python pic.py > pic2.jpg"
The resulting pic2.jpg is not identical to the original. I looked at it in
a hex editor, and it seems to be identical with the original pic.jpg, except
for several 0D (carraige return) characters inserted throughout the file.

I tried this with Python 2.2.1 and 2.3.2. What's going on?
Thanks in advance,
-Noah
 
M

Michael Hudson

Mr. Costington said:
Hi all, I was trying to hava a CGI script return an image, but it was coming
back corrupted. So I tried this simple non-CGI test and still get errors:

import sys
image = open('pic.jpg','rb').read()
sys.stdout.write(image)

When I run this like "python pic.py > pic2.jpg"
The resulting pic2.jpg is not identical to the original. I looked at it in
a hex editor, and it seems to be identical with the original pic.jpg, except
for several 0D (carraige return) characters inserted throughout the file.

sys.stdout is not usually a binary-mode file.

Cheers,
mwh
 
W

Werner Schiendl

Hi,

Mr. Costington said:
When I run this like "python pic.py > pic2.jpg"
The resulting pic2.jpg is not identical to the original. I looked at it in
a hex editor, and it seems to be identical with the original pic.jpg, except
for several 0D (carraige return) characters inserted throughout the file.

I tried this with Python 2.2.1 and 2.3.2. What's going on?

The sys.stdout is obviously open in text (not binary) mode.

When you write "\n" (linefeed) you'll get "\r\n" (carriage return +
linefeed) in the destination.

hth

Werner
 
A

Alex Martelli

Michael said:
...
sys.stdout is not usually a binary-mode file.

Right; one can change that with the -u switch to python (e.g., starting
the cgi script with
#!c:\python23\python.exe -u
if one's webserver recognizes and applies hashbang conventions).


Alex
 
M

Mr. Costington

Alex Martelli said:
Right; one can change that with the -u switch to python (e.g., starting
the cgi script with
#!c:\python23\python.exe -u
if one's webserver recognizes and applies hashbang conventions).

Thanks. My server ignores hashbangs, but I was able to set sys.stdout to
binary-mode with the following line:
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,462
Latest member
ChanaLipsc

Latest Threads

Top