PIL and format conversions -- Noobie.
fredrik at pythonware.com
Tue Dec 14 14:32:15 CET 2004
Ron Phillips wrote:
>I have a monster jpg (128 mb) that comprises a handful of colors (20 or
> so, max). It should never have been compressed with jpeg compression, as
> I understand it. It should have been a png or gif, since they are made
> to handle blocks of a few colors.
if you compress an image that originally had 20 or so colors, max, as JPEG, and
then decompress it, you get a lot more colors in the resulting image. an example:
>>> import Image
let's load an arbitrary color image:
>>> im = Image.open("lenna.ppm")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: len() of unsized object
by default, getcolors() returns None if the image contains
more than 256 colors. let's try raising that limit:
okay, we have some 120000 unique colors in this RGB image.
let's cut the number of colors down to 20:
>>> im = im.quantize(20)
and roundtrip via JPEG:
>>> im = Image.open("out.jpg")
> I used PIL to convert it to png and to gif, and it got even bigger (6 -
> 8 x) -- am I using PIL wrong, or is PIL the wrong tool? If so, how
> should I use PIL so it best compresses the outfile? Or, what tool should
> I use?
this might work:
im = Image.open("myimage.jpg")
im = im.convert(
"P", dither=Image.NONE, palette=Image.ADAPTIVE, colors=20
(trying various colors settings might be a good idea; if you leave it out, you'll
get no more than 256 colors).
More information about the Python-list