@@ -1966,10 +1966,6 @@ def save(self, fp, format=None, **params):
19661966 # may mutate self!
19671967 self ._ensure_mutable ()
19681968
1969- save_all = params .pop ('save_all' , False )
1970- self .encoderinfo = params
1971- self .encoderconfig = ()
1972-
19731969 preinit ()
19741970
19751971 ext = os .path .splitext (filename )[1 ].lower ()
@@ -1984,11 +1980,20 @@ def save(self, fp, format=None, **params):
19841980
19851981 if format .upper () not in SAVE :
19861982 init ()
1987- if save_all :
1983+ if params . pop ( ' save_all' , False ) :
19881984 save_handler = SAVE_ALL [format .upper ()]
19891985 else :
19901986 save_handler = SAVE [format .upper ()]
19911987
1988+ if params .get ('convert_mode' ):
1989+ plugin = sys .modules [save_handler .__module__ ]
1990+ converted_im = self ._convert_mode (plugin , params )
1991+ if converted_im :
1992+ return converted_im .save (fp , format , ** params )
1993+
1994+ self .encoderinfo = params
1995+ self .encoderconfig = ()
1996+
19921997 if open_fp :
19931998 if params .get ('append' , False ):
19941999 fp = builtins .open (filename , "r+b" )
@@ -2004,6 +2009,37 @@ def save(self, fp, format=None, **params):
20042009 if open_fp :
20052010 fp .close ()
20062011
2012+ def _convert_mode (self , plugin , params ):
2013+ if not hasattr (plugin , '_convert_mode' ):
2014+ return
2015+ new_mode = plugin ._convert_mode (self )
2016+ if self .mode == 'LA' and new_mode == 'P' :
2017+ alpha = self .getchannel ('A' )
2018+ # Convert the image into P mode but only use 255 colors
2019+ # in the palette out of 256.
2020+ im = self .convert ('L' ) \
2021+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
2022+ # Set all pixel values below 128 to 255, and the rest to 0.
2023+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
2024+ # Paste the color of index 255 and use alpha as a mask.
2025+ im .paste (255 , mask )
2026+ # The transparency index is 255.
2027+ im .info ['transparency' ] = 255
2028+ return im
2029+
2030+ elif self .mode == 'I' :
2031+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
2032+ return im .convert (new_mode ) if new_mode != 'L' else im
2033+
2034+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
2035+ fill_color = params .get ('fill_color' , 'white' )
2036+ background = new (new_mode , self .size , fill_color )
2037+ background .paste (self , self .getchannel ('A' ))
2038+ return background
2039+
2040+ elif new_mode :
2041+ return self .convert (new_mode )
2042+
20072043 def seek (self , frame ):
20082044 """
20092045 Seeks to the given frame in this sequence file. If you seek
0 commit comments