Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pillow ImagePalette Module

Pillow ImagePalette Module

ImagePalette is a module in the Python Pillow library mainly used for handling image palettes. A palette is a set of predefined colors, commonly used in indexed images (such as GIF format) to optimize storage and display efficiency.

code>ImagePalette module focuses on the creation, modification and application of palettes.

Import syntax:



from PIL import Image


Main methods of ImagePalette

The following table lists the ImagePalette The core methods of the module and their functional descriptions:

Method Description Parameter Description Return Value
ImagePalette(mode='RGB', palette=None) Create a new palette object mode: Color mode (such as 'RGB', 'RGBA')
palette: Optional, initial palette data (byte sequence) ImagePalette object
getcolor(color) Get the index of a specified color in the palette color: Color value (such as (255, 0, 0) representing red) Return the index of the color (int), or return if it does not exist None
getdata() Get the raw byte data of the palette None Return the byte data of the palette (bytes)
tobytes() Convert the palette to a byte sequence None Return the byte data of the palette (bytes)
tostring() (Deprecated) Same as tobytes() None Return the byte data of the palette (bytes)

Usage examples

Create a palette

Example

from

PIL

import

ImagePalette

Create an RGB mode palette

palette

=

ImagePalette

(

mode

=

'RGB'

)

Add colors to the palette

palette.

getcolor

(

(

255

,

0

,

0

)

)

 

Add red

palette.

getcolor

(

(

0

,

255

,

0

)

)

 

Add green

palette.

getcolor

(

(

0

,

0

,

255

)

)

 

Add blue

Get palette data

print

(

palette.

getdata

(

)

)

 

Output the byte data of the palette

Apply palette to image

Example

from

PIL

import

Image

Create a 100x100 indexed image

img

=

Image.

new

(

'P'

,

(

100

,

100

)

)

Set the palette

img.

putpalette

(

palette.

getdata

(

)

)

Save the image

img.

save

(

'palette_image.gif'

)


Common questions

What is the purpose of a palette?

Palettes are used to optimize image storage and display, especially in indexed images (such as GIF), where each pixel stores a color index rather than the actual color value, thereby reducing file size.

How to view the colors in a palette?

can be used via getdata() method to get the byte data of the palette, then parse it into RGB values.

Does the palette support transparent colors?

If the palette mode is RGBA, it can include a transparency channel (Alpha channel).