@@ -2123,10 +2123,6 @@ def save(self, fp, format=None, **params):
21232123 # may mutate self!
21242124 self ._ensure_mutable ()
21252125
2126- save_all = params .pop ("save_all" , False )
2127- self .encoderinfo = params
2128- self .encoderconfig = ()
2129-
21302126 preinit ()
21312127
21322128 ext = os .path .splitext (filename )[1 ].lower ()
@@ -2141,11 +2137,20 @@ def save(self, fp, format=None, **params):
21412137
21422138 if format .upper () not in SAVE :
21432139 init ()
2144- if save_all :
2140+ if params . pop ( ' save_all' , False ) :
21452141 save_handler = SAVE_ALL [format .upper ()]
21462142 else :
21472143 save_handler = SAVE [format .upper ()]
21482144
2145+ if params .get ('convert_mode' ):
2146+ plugin = sys .modules [save_handler .__module__ ]
2147+ converted_im = self ._convert_mode (plugin , params )
2148+ if converted_im :
2149+ return converted_im .save (fp , format , ** params )
2150+
2151+ self .encoderinfo = params
2152+ self .encoderconfig = ()
2153+
21492154 if open_fp :
21502155 if params .get ("append" , False ):
21512156 # Open also for reading ("+"), because TIFF save_all
@@ -2161,6 +2166,37 @@ def save(self, fp, format=None, **params):
21612166 if open_fp :
21622167 fp .close ()
21632168
2169+ def _convert_mode (self , plugin , params ):
2170+ if not hasattr (plugin , '_convert_mode' ):
2171+ return
2172+ new_mode = plugin ._convert_mode (self )
2173+ if self .mode == 'LA' and new_mode == 'P' :
2174+ alpha = self .getchannel ('A' )
2175+ # Convert the image into P mode but only use 255 colors
2176+ # in the palette out of 256.
2177+ im = self .convert ('L' ) \
2178+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
2179+ # Set all pixel values below 128 to 255, and the rest to 0.
2180+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
2181+ # Paste the color of index 255 and use alpha as a mask.
2182+ im .paste (255 , mask )
2183+ # The transparency index is 255.
2184+ im .info ['transparency' ] = 255
2185+ return im
2186+
2187+ elif self .mode == 'I' :
2188+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
2189+ return im .convert (new_mode ) if new_mode != 'L' else im
2190+
2191+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
2192+ fill_color = params .get ('fill_color' , 'white' )
2193+ background = new (new_mode , self .size , fill_color )
2194+ background .paste (self , self .getchannel ('A' ))
2195+ return background
2196+
2197+ elif new_mode :
2198+ return self .convert (new_mode )
2199+
21642200 def seek (self , frame ):
21652201 """
21662202 Seeks to the given frame in this sequence file. If you seek
0 commit comments