Skip to content

Commit 9f0e454

Browse files
committed
ANI: Reduce Pillow frames to RGB when opaque
In some cases, such as GIF output, Pillow must convert to P (palette) mode. Unfortunately, when done on RGBA images, this can lose some colour information (cf, python-pillow/Pillow#6832) But when the image starts in RGB mode, the conversion to P mode works better, so convert frames to RGB when they don't have any transparent pixels. Fixes matplotlib#29190
1 parent 84fbae8 commit 9f0e454

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

lib/matplotlib/animation.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -492,8 +492,15 @@ def grab_frame(self, **savefig_kwargs):
492492
buf = BytesIO()
493493
self.fig.savefig(
494494
buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
495-
self._frames.append(Image.frombuffer(
496-
"RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1))
495+
im = Image.frombuffer(
496+
"RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)
497+
if im.getextrema()[3][0] < 255:
498+
# This frame has transparency, so we'll just add it as is.
499+
self._frame.append(im)
500+
else:
501+
# Without transparency, we switch to RGB mode, which converts to P mode a
502+
# little better if needed (specifically, this helps with GIF output.)
503+
self._frames.append(im.convert("RGB"))
497504

498505
def finish(self):
499506
self._frames[0].save(

0 commit comments

Comments
 (0)