Skip to content

Commit

Permalink
ANI: Reduce Pillow frames to RGB when opaque
Browse files Browse the repository at this point in the history
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
  • Loading branch information
QuLogic committed Dec 5, 2024
1 parent 84fbae8 commit 9f0e454
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,8 +492,15 @@ def grab_frame(self, **savefig_kwargs):
buf = BytesIO()
self.fig.savefig(
buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
self._frames.append(Image.frombuffer(
"RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1))
im = Image.frombuffer(
"RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)
if im.getextrema()[3][0] < 255:
# This frame has transparency, so we'll just add it as is.
self._frame.append(im)
else:
# Without transparency, we switch to RGB mode, which converts to P mode a
# little better if needed (specifically, this helps with GIF output.)
self._frames.append(im.convert("RGB"))

def finish(self):
self._frames[0].save(
Expand Down

0 comments on commit 9f0e454

Please sign in to comment.