@@ -2133,10 +2133,6 @@ def save(self, fp, format=None, **params):
21332133 # may mutate self!
21342134 self ._ensure_mutable ()
21352135
2136- save_all = params .pop ("save_all" , False )
2137- self .encoderinfo = params
2138- self .encoderconfig = ()
2139-
21402136 preinit ()
21412137
21422138 ext = os .path .splitext (filename )[1 ].lower ()
@@ -2151,11 +2147,20 @@ def save(self, fp, format=None, **params):
21512147
21522148 if format .upper () not in SAVE :
21532149 init ()
2154- if save_all :
2150+ if params . pop ( ' save_all' , False ) :
21552151 save_handler = SAVE_ALL [format .upper ()]
21562152 else :
21572153 save_handler = SAVE [format .upper ()]
21582154
2155+ if params .get ('convert_mode' ):
2156+ plugin = sys .modules [save_handler .__module__ ]
2157+ converted_im = self ._convert_mode (plugin , params )
2158+ if converted_im :
2159+ return converted_im .save (fp , format , ** params )
2160+
2161+ self .encoderinfo = params
2162+ self .encoderconfig = ()
2163+
21592164 if open_fp :
21602165 if params .get ("append" , False ):
21612166 # Open also for reading ("+"), because TIFF save_all
@@ -2171,6 +2176,37 @@ def save(self, fp, format=None, **params):
21712176 if open_fp :
21722177 fp .close ()
21732178
2179+ def _convert_mode (self , plugin , params ):
2180+ if not hasattr (plugin , '_convert_mode' ):
2181+ return
2182+ new_mode = plugin ._convert_mode (self )
2183+ if self .mode == 'LA' and new_mode == 'P' :
2184+ alpha = self .getchannel ('A' )
2185+ # Convert the image into P mode but only use 255 colors
2186+ # in the palette out of 256.
2187+ im = self .convert ('L' ) \
2188+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
2189+ # Set all pixel values below 128 to 255, and the rest to 0.
2190+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
2191+ # Paste the color of index 255 and use alpha as a mask.
2192+ im .paste (255 , mask )
2193+ # The transparency index is 255.
2194+ im .info ['transparency' ] = 255
2195+ return im
2196+
2197+ elif self .mode == 'I' :
2198+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
2199+ return im .convert (new_mode ) if new_mode != 'L' else im
2200+
2201+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
2202+ fill_color = params .get ('fill_color' , 'white' )
2203+ background = new (new_mode , self .size , fill_color )
2204+ background .paste (self , self .getchannel ('A' ))
2205+ return background
2206+
2207+ elif new_mode :
2208+ return self .convert (new_mode )
2209+
21742210 def seek (self , frame ):
21752211 """
21762212 Seeks to the given frame in this sequence file. If you seek
0 commit comments