Created
August 11, 2015 23:55
-
-
Save JPLeBreton/88d475eb1c388ba3ab83 to your computer and use it in GitHub Desktop.
PIL/Pillow test: crash converting transparent GIF to RGB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.path | |
from PIL import Image | |
# image URLs for the two images used below: | |
# http://vectorpoem.com/images/grad.gif | |
# http://vectorpoem.com/images/grad2.gif | |
def convert_image(src_img_filename): | |
# convert source image to RGB, then convert it to an arbitrary test palette | |
print('reading %s...' % src_img_filename) | |
out_img = Image.open(src_img_filename).convert('RGB') | |
pal_img = Image.new('P', (1, 1)) | |
colors = [0, 0, 0, 128, 128, 128, 255, 0, 0] | |
# PIL requires a tuple of exactly 768 integers for a palette :/ | |
while len(colors) < 768: | |
colors += [0] | |
pal_img.putpalette(tuple(colors)) | |
out_img = out_img.quantize(palette=pal_img) | |
out_img = out_img.convert('RGB') | |
print('conversion succeded') | |
out_img.save('%s_out.png' % os.path.splitext(src_img_filename)[0]) | |
print('image written') | |
# test image 1: non-transparent non-animated GIF | |
convert_image('grad.gif') | |
# test image 2: transparent non-animated GIF | |
convert_image('grad2.gif') | |
# | |
# so why does image #1 crash but not image #2 ?!? | |
# |
Fix for this is to remove transparency from the GIF before converting, eg
out_img.info['transparency'] = 0
Thanks @WoTToW!
The crash that happens in PIL could well be a bug; I should file it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Program output on my machine:
[jpl@shada pil]$ python pil_test.py
reading grad.gif...
conversion succeded
image written
reading grad2.gif...
Traceback (most recent call last):
File "pil_test.py", line 23, in
convert_image('grad2.gif')
File "pil_test.py", line 16, in convert_image
out_img = out_img.convert('RGB')
File "/usr/lib/python3.4/site-packages/PIL/Image.py", line 890, in convert
trns_im.putpixel((0, 0), t)
File "/usr/lib/python3.4/site-packages/PIL/Image.py", line 1536, in putpixel
return self.im.putpixel(xy, value)
TypeError: an integer is required (got type tuple)