@@ -2176,10 +2176,6 @@ def save(self, fp, format=None, **params):
21762176 # may mutate self!
21772177 self ._ensure_mutable ()
21782178
2179- save_all = params .pop ("save_all" , False )
2180- self .encoderinfo = params
2181- self .encoderconfig = ()
2182-
21832179 preinit ()
21842180
21852181 ext = os .path .splitext (filename )[1 ].lower ()
@@ -2194,11 +2190,20 @@ def save(self, fp, format=None, **params):
21942190
21952191 if format .upper () not in SAVE :
21962192 init ()
2197- if save_all :
2193+ if params . pop ( ' save_all' , False ) :
21982194 save_handler = SAVE_ALL [format .upper ()]
21992195 else :
22002196 save_handler = SAVE [format .upper ()]
22012197
2198+ if params .get ('convert_mode' ):
2199+ plugin = sys .modules [save_handler .__module__ ]
2200+ converted_im = self ._convert_mode (plugin , params )
2201+ if converted_im :
2202+ return converted_im .save (fp , format , ** params )
2203+
2204+ self .encoderinfo = params
2205+ self .encoderconfig = ()
2206+
22022207 if open_fp :
22032208 if params .get ("append" , False ):
22042209 # Open also for reading ("+"), because TIFF save_all
@@ -2214,6 +2219,37 @@ def save(self, fp, format=None, **params):
22142219 if open_fp :
22152220 fp .close ()
22162221
2222+ def _convert_mode (self , plugin , params ):
2223+ if not hasattr (plugin , '_convert_mode' ):
2224+ return
2225+ new_mode = plugin ._convert_mode (self )
2226+ if self .mode == 'LA' and new_mode == 'P' :
2227+ alpha = self .getchannel ('A' )
2228+ # Convert the image into P mode but only use 255 colors
2229+ # in the palette out of 256.
2230+ im = self .convert ('L' ) \
2231+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
2232+ # Set all pixel values below 128 to 255, and the rest to 0.
2233+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
2234+ # Paste the color of index 255 and use alpha as a mask.
2235+ im .paste (255 , mask )
2236+ # The transparency index is 255.
2237+ im .info ['transparency' ] = 255
2238+ return im
2239+
2240+ elif self .mode == 'I' :
2241+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
2242+ return im .convert (new_mode ) if new_mode != 'L' else im
2243+
2244+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
2245+ fill_color = params .get ('fill_color' , 'white' )
2246+ background = new (new_mode , self .size , fill_color )
2247+ background .paste (self , self .getchannel ('A' ))
2248+ return background
2249+
2250+ elif new_mode :
2251+ return self .convert (new_mode )
2252+
22172253 def seek (self , frame ):
22182254 """
22192255 Seeks to the given frame in this sequence file. If you seek
0 commit comments