@@ -1915,10 +1915,6 @@ def save(self, fp, format=None, **params):
19151915 # may mutate self!
19161916 self .load ()
19171917
1918- save_all = params .pop ('save_all' , False )
1919- self .encoderinfo = params
1920- self .encoderconfig = ()
1921-
19221918 preinit ()
19231919
19241920 ext = os .path .splitext (filename )[1 ].lower ()
@@ -1933,11 +1929,20 @@ def save(self, fp, format=None, **params):
19331929
19341930 if format .upper () not in SAVE :
19351931 init ()
1936- if save_all :
1932+ if params . pop ( ' save_all' , False ) :
19371933 save_handler = SAVE_ALL [format .upper ()]
19381934 else :
19391935 save_handler = SAVE [format .upper ()]
19401936
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+
19411946 if open_fp :
19421947 if params .get ('append' , False ):
19431948 fp = builtins .open (filename , "r+b" )
@@ -1953,6 +1958,37 @@ def save(self, fp, format=None, **params):
19531958 if open_fp :
19541959 fp .close ()
19551960
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+
19561992 def seek (self , frame ):
19571993 """
19581994 Seeks to the given frame in this sequence file. If you seek
0 commit comments