Closed noclev closed 2 years ago
The way that I read the other issue, I don't think quantize()
was supposed to be a solution, just an explanation - the GIF format can only save 256 colours per frame, and quantize()
converts an image to have no more than 256 colors. The comment was saying that this is what happens when Pillow tries to make sure that the image fits within the GIF format.
As for a solution to your problem, how about this code? If the image has 256 colors or less, it will convert the pixels directly from RGBA to P. It can only handle 1 transparency color, but that is a limitation of the GIF format.
from PIL import Image
im = Image.open('./input.gif').convert('RGBA')
if len(im.getcolors()) <= 256:
px = im.load()
new = Image.new('P', im.size)
new_px = new.load()
for x in range(im.width):
for y in range(im.height):
c = px[x, y]
i = new.palette.getcolor(c)
new_px[x, y] = i
if c[3] == 0:
new.info["transparency"] = i
im = new
im.save('output.gif')
Tons of apologies for my misunderstanding, and thank you so much for the solution, this is what I have been looking for!
What did you do?
When I try to read an image without a background, convert to RGBA, then save it back in the same format (gif) - the quality is lost. I followed the advice from previous issue #3059 and am somewhat duplicating it here, because that solution does not work for me. (I really hope I have not missed something)
input.gif:
What did you expect to happen?
I expected output.gif to be of the same quality as input.gif
What actually happened?
output.gif is of considerably worse quality output.gif:
What are your OS, Python and Pillow versions?