I'm wondering if it's possible to scale an animated GIF image using PIL. In particular Plone’s archetypes ImageField currently loses the animation from images scaled using its scale method:
def scale(self, data, w, h, default_format = 'PNG'):
""" scale image (with material from ImageTag_Hotfix)"""
#make sure we have valid int's
size = int(w), int(h)
original_file=StringIO(data)
image = PIL.Image.open(original_file)
# consider image mode when scaling
# source images can be mode '1','L,','P','RGB(A)'
# convert to greyscale or RGBA before scaling
# preserve palletted mode (but not pallette)
# for palletted-only image formats, e.g. GIF
# PNG compression is OK for RGBA thumbnails
original_mode = image.mode
img_format = image.format and image.format or default_format
if original_mode == '1':
image = image.convert('L')
elif original_mode == 'P':
image = image.convert('RGBA')
image.thumbnail(size, self.pil_resize_algo)
# decided to only preserve palletted mode
# for GIF, could also use image.format in ('GIF','PNG')
if original_mode == 'P' and img_format == 'GIF':
image = image.convert('P')
thumbnail_file = StringIO()
# quality parameter doesn't affect lossless formats
image.save(thumbnail_file, img_format, quality=self.pil_quality)
thumbnail_file.seek(0)
return thumbnail_file, img_format.lower()
I know how to identify a animated GIF: The following evaluates to True image.format == 'GIF' and image.seek(image.tell()+1)
. I’ve tried not converting to RGBA mode but that doesn't work.
Background: On our Plone instance we've modified the default image type to set the original_size attribute of its image field to force all images to scaled with an appropriate quality setting. This works great for jpegs but means we currently can't upload animated GIFs