[Image-SIG] Opening and saving quality JPEG files

Christian M. Jensen christianj at implicitnetworks.com
Thu Jun 23 22:34:54 CEST 2005

Pre-calculating the content length and informing the browser is a good
thing too.

Search Google for "Content-Length" header info.

-----Original Message-----
From: image-sig-bounces at python.org [mailto:image-sig-bounces at python.org]
On Behalf Of Chris Cogdon
Sent: Thursday, June 23, 2005 1:09 PM
To: Rob Ballou
Cc: image-sig at python.org
Subject: Re: [Image-SIG] Opening and saving quality JPEG files

On Jun 23, 2005, at 12:54, Rob Ballou wrote:

> Hello,
> I'm new to using PIL and I have what I hope is a quick question.
> I have created a script for displaying images to a web browser and I
> have noticed that the quality PIL saves JPEGs isn't entirely what I'm
> after. When displaying thumbnails (the main use of the script), the
> quality is great. But when displaying a full size image without
> modification, I noticed that there is some new JPEG compression taking
> place (there are pronounced JPEG compression artifacts).
> The code that I have is:
> im = Image.open(file)
> print "Content-type: image/%s\r\n" % im.format.lower()
> out= cStringIO.StringIO()
> im.save(out, format, quailty=100, optimize=1)
> out.reset()
> print out.read()
> out.close()
> Changing quality and the optimized attributes have little to no effect
> on the visual appearance of the image. I've tried to read the file
> directly in binary mode and print that back to the browser, but it can
> not display the image.
> I'm not really sure if I am going about these changes in the best
> manner. Thanks in advance for any help.

If you're not interested in processing the image, then there's no 
reason to run it through PIL

Try this:

im = Image.open(file)

print "Content-type: image/%s\n" % im.format.lower()
sys.stdout.write ( open(file).read() )

Ie... open it once so that PIL can get the format, then open it again 
to send through the web server.

I'm using 'write' to avoid the extra newline at the end of the data 
(which is a bad thing to do).

I'm also sending only a \n... the web server will automatically turn 
all newlines (\n) into NVT-ASCII newlines (\r\n). You don't want an 
extra \r in there.

    ("`-/")_.-'"``-._        Chris Cogdon <chris at cogdon.org>
     . . `; -._    )-;-,_`)
    (v_,)'  _  )`-.\  ``-'
   _.- _..-_/ / ((.'
((,.-'   ((,/   fL

Image-SIG maillist  -  Image-SIG at python.org

More information about the Image-SIG mailing list