@@ -2099,10 +2099,6 @@ def save(self, fp, format=None, **params):
20992099 # may mutate self!
21002100 self ._ensure_mutable ()
21012101
2102- save_all = params .pop ("save_all" , False )
2103- self .encoderinfo = params
2104- self .encoderconfig = ()
2105-
21062102 preinit ()
21072103
21082104 ext = os .path .splitext (filename )[1 ].lower ()
@@ -2117,11 +2113,20 @@ def save(self, fp, format=None, **params):
21172113
21182114 if format .upper () not in SAVE :
21192115 init ()
2120- if save_all :
2116+ if params . pop ( ' save_all' , False ) :
21212117 save_handler = SAVE_ALL [format .upper ()]
21222118 else :
21232119 save_handler = SAVE [format .upper ()]
21242120
2121+ if params .get ('convert_mode' ):
2122+ plugin = sys .modules [save_handler .__module__ ]
2123+ converted_im = self ._convert_mode (plugin , params )
2124+ if converted_im :
2125+ return converted_im .save (fp , format , ** params )
2126+
2127+ self .encoderinfo = params
2128+ self .encoderconfig = ()
2129+
21252130 if open_fp :
21262131 if params .get ("append" , False ):
21272132 # Open also for reading ("+"), because TIFF save_all
@@ -2137,6 +2142,37 @@ def save(self, fp, format=None, **params):
21372142 if open_fp :
21382143 fp .close ()
21392144
2145+ def _convert_mode (self , plugin , params ):
2146+ if not hasattr (plugin , '_convert_mode' ):
2147+ return
2148+ new_mode = plugin ._convert_mode (self )
2149+ if self .mode == 'LA' and new_mode == 'P' :
2150+ alpha = self .getchannel ('A' )
2151+ # Convert the image into P mode but only use 255 colors
2152+ # in the palette out of 256.
2153+ im = self .convert ('L' ) \
2154+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
2155+ # Set all pixel values below 128 to 255, and the rest to 0.
2156+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
2157+ # Paste the color of index 255 and use alpha as a mask.
2158+ im .paste (255 , mask )
2159+ # The transparency index is 255.
2160+ im .info ['transparency' ] = 255
2161+ return im
2162+
2163+ elif self .mode == 'I' :
2164+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
2165+ return im .convert (new_mode ) if new_mode != 'L' else im
2166+
2167+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
2168+ fill_color = params .get ('fill_color' , 'white' )
2169+ background = new (new_mode , self .size , fill_color )
2170+ background .paste (self , self .getchannel ('A' ))
2171+ return background
2172+
2173+ elif new_mode :
2174+ return self .convert (new_mode )
2175+
21402176 def seek (self , frame ):
21412177 """
21422178 Seeks to the given frame in this sequence file. If you seek
0 commit comments