Skip to content

Instantly share code, notes, and snippets.

@devilholk
Created June 1, 2019 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devilholk/a85b8cb2a04d55fdea0c9419d4343c27 to your computer and use it in GitHub Desktop.
Save devilholk/a85b8cb2a04d55fdea0c9419d4343c27 to your computer and use it in GitHub Desktop.
Testing custom PNG writer for PIL that allows non 256 size palettes
import PIL.Image, our_png_save
im = PIL.Image.new('RGB', (256, 256))
p = im.load()
for y in range(256):
for x in range(256):
p[x,y] = (x, y, (x * y) >> 8)
colors = set()
for y in range(256):
for x in range(256):
colors.add(p[x, y])
print(len(colors)) #I have 65536 colors
def save_to_png_with_limited_palette(im, filename, count=256):
out = im.convert('P', palette=PIL.Image.ADAPTIVE, colors=count)
out.palette.palette = out.palette.palette[:count*3] #Truncate palette
out.save(filename)
save_to_png_with_limited_palette(im, 't1.png', 63)
test = PIL.Image.open('t1.png')
print(len(test.palette.palette) // 3) #I have 63 colors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment