You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Convert image to supported mode before saving #2663
We need explicit method to automatically convert image to one of the supported modes for saving formats. Affects #2609 and others. Maybe it should be part of ImagePlugins.
This is a good start point:
deffix_mode(image, new_format, fill_color='white'):
old_mode=image.modeifold_modein ('RGBA', 'LA') andnew_format=='GIF':
alpha=image.getchannel('A')
# Convert the image into P mode but only use 255 colors# in the palette out of 256.image=image.convert(old_mode[:-1]) \
.convert('P', palette=Image.ADAPTIVE, colors=255)
# Set all pixel values below 128 to 255, and the rest to 0.mask=Image.eval(alpha, lambdapx: 255ifpx<128else0)
# Paste the color of index 255 and use alpha as a mask.image.paste(255, mask)
# The transparency index is 255.image.info['transparency'] =255returnimageifold_mode=='CMYK'andnew_formatin ('PNG', 'WEBP', 'GIF'):
returnimage.convert('RGB')
ifold_mode=='I'andnew_formatin ('JPEG', 'GIF', 'WEBP'):
image=image.point([i//256foriinrange(65536)], 'L')
old_mode=image.modeifold_mode=='P'andnew_formatin ('JPEG', 'WEBP'):
# PIL loses palette attribute during crop. So we use low-level api.alpha='A'inimage.im.getpalettemode()
image=image.convert('RGBA'ifalphaelse'RGB')
old_mode=image.modeifold_modein ('RGBA', 'LA') andnew_format=='JPEG':
background=Image.new(old_mode[:-1], image.size, fill_color)
background.paste(image, image.getchannel('A'))
image=backgroundold_mode=image.mode# Pillow doesn't support L modes for webp for now.ifold_modein ('L', 'LA') andnew_format=='WEBP':
image=image.convert('RGB'+old_mode[1:])
old_mode=image.modereturnimage
Reacted by Roland van Laar, Konstantin Kopachev, Jeffrey 'Alex' Clark, LidiyaNorman, nypava and Cees Timmerman
Activity
aclark4life commentedon Apr 1, 2018
@homm How about a PR for this?
hugovk commentedon Jun 10, 2018
@homm Would you like to have a look at @radarhere's PR #3172?
aclark4life commentedon May 11, 2019
Or alternatively @homm would you look at it even if you wouldn't like to do it? 😄
aclark4life commentedon May 11, 2019
@hugovk @radarhere If you still think this can go in and no objection from @wiredfool or @homm I'd probably just merge it.
homm commentedon May 12, 2019
I've reviewed the PR, it is very close to what I meant.
radarhere commentedon Nov 9, 2026
#3172 has been sitting open for quite a while. I'm going to close this for lack of interest.