@@ -1915,12 +1915,6 @@ def save(self, fp, format=None, **params):
19151915 # may mutate self!
19161916 self .load ()
19171917
1918- save_all = False
1919- if 'save_all' in params :
1920- save_all = params .pop ('save_all' )
1921- self .encoderinfo = params
1922- self .encoderconfig = ()
1923-
19241918 preinit ()
19251919
19261920 ext = os .path .splitext (filename )[1 ].lower ()
@@ -1935,11 +1929,20 @@ def save(self, fp, format=None, **params):
19351929
19361930 if format .upper () not in SAVE :
19371931 init ()
1938- if save_all :
1932+ if params . pop ( ' save_all' , False ) :
19391933 save_handler = SAVE_ALL [format .upper ()]
19401934 else :
19411935 save_handler = SAVE [format .upper ()]
19421936
1937+ if params .get ('convert_mode' ):
1938+ plugin = sys .modules [save_handler .__module__ ]
1939+ converted_im = self ._convert_mode (plugin , params )
1940+ if converted_im :
1941+ return converted_im .save (fp , format , ** params )
1942+
1943+ self .encoderinfo = params
1944+ self .encoderconfig = ()
1945+
19431946 if open_fp :
19441947 if params .get ('append' , False ):
19451948 fp = builtins .open (filename , "r+b" )
@@ -1955,6 +1958,37 @@ def save(self, fp, format=None, **params):
19551958 if open_fp :
19561959 fp .close ()
19571960
1961+ def _convert_mode (self , plugin , params ):
1962+ if not hasattr (plugin , '_convert_mode' ):
1963+ return
1964+ new_mode = plugin ._convert_mode (self )
1965+ if self .mode == 'LA' and new_mode == 'P' :
1966+ alpha = self .getchannel ('A' )
1967+ # Convert the image into P mode but only use 255 colors
1968+ # in the palette out of 256.
1969+ im = self .convert ('L' ) \
1970+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
1971+ # Set all pixel values below 128 to 255, and the rest to 0.
1972+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
1973+ # Paste the color of index 255 and use alpha as a mask.
1974+ im .paste (255 , mask )
1975+ # The transparency index is 255.
1976+ im .info ['transparency' ] = 255
1977+ return im
1978+
1979+ elif self .mode == 'I' :
1980+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
1981+ return im .convert (new_mode ) if new_mode != 'L' else im
1982+
1983+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
1984+ fill_color = params .get ('fill_color' , 'white' )
1985+ background = new (new_mode , self .size , fill_color )
1986+ background .paste (self , self .getchannel ('A' ))
1987+ return background
1988+
1989+ elif new_mode :
1990+ return self .convert (new_mode )
1991+
19581992 def seek (self , frame ):
19591993 """
19601994 Seeks to the given frame in this sequence file. If you seek
0 commit comments