Optimize .png images with PIL

10,818

The RGBA mode is the only mode that supports transparency, and it is necessarily 32 bits:

1 (1-bit pixels, black and white, stored with one pixel per byte)

L (8-bit pixels, black and white)

P (8-bit pixels, mapped to any other mode using a color palette)

RGB (3x8-bit pixels, true color)

RGBA (4x8-bit pixels, true color with transparency mask)

I would recommend you to store your image with a non-transparent 1 mode and use the image itself as a mask. If you give your image with mode 1 as a mask on your image, black pixels will stay and white ones will be transparent. This will take 32 times less space without any loss of information.

You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.

It will look something like this:

your_transparent_image.paste(bw_image, mask=bw_image)

where bw_image is your black and white text.

Share:
10,818

Related videos on Youtube

Blemone
Author by

Blemone

Updated on June 04, 2022

Comments

  • Blemone
    Blemone almost 2 years

    All I need is to create a .png image with transparent background, draw some text in black on it and save it using img.save('target.png', option='optimize')

    It looks like PIL saves .png images in 32-bit mode automatically. Can I reduce the color depth while not making the output images look much worse before saving? Since it contains only black text and transparent background, I think reducing the color depth would greatly reduce file size.

    • Martijn Pieters
      Martijn Pieters almost 12 years
      Note: the correct syntax for setting the optimize flag is: img.save('target.png', optimize=True).
    • martineau
      martineau
      @StevenRoose: Yes, try this link.