[Image-SIG] Re: IMAGE WEIGHT IN PIL

Fredrik Lundh fredrik at pythonware.com
Sat Feb 21 06:47:59 EST 2004


Gerard Coing wrote:

> New to Python & PIL
> I have to do image batch converting and resizing from TIFF to JPEG with
> a MAXIMUM WEIGHT (150 Ko) for the output.
> Could someone tell me what is the syntax to get the weight of an output
> image and if there is another way than looping through the output until
> the desired weight is got.

I assume you mean image size (in bytes).

unlike many video formats, JPEG doesn't support "constant bitrate", so the
size of the output file will vary depending on the contents of the image.

a typical colour image is compressed about 20 times at the default quality,
so your 150k limit corresponds to a 1000x1000-pixel image.  If the image is
only slightly larger, you can try dropping the quality somewhat.  However,
if the image is much larger, it's probably better to resize it than to tweak
the JPEG quality settings.  I'd try something like:

    width, height = im.size
    if width > 3000 or height > 3000:
        # really large image; resize before compression
        im.thumbnail((1000, 1000), Image.ANTIALIAS)
    save with default quality (75)
    if filesize > 150k:
        if width > 2000 or height > 2000:
                # large image; dropping the quality isn't likely to help
                im.thumbnail((1000, 1000), Image.ANTIALIAS)
                save with default quality (75)
                if filesize > 150k:
                    save with quality=50
        else:
                # try dropping the quality before resizing
                save with quality=50
                if filesize > 150k:
                    im.thumbnail((1000, 1000), Image.BICUBIC)
                    save with default quality (75)
                    if filesize > 150k:
                        save with quality=50
                        # if the 150k limit is absolute, add more tests here

(tweak the numbers as necessary)

(if most images are rectangular, it's probably a good idea to calculate
the "thumbnail" size based on the aspect ratio for each image)

</F>






More information about the Image-SIG mailing list