@@ -1934,10 +1934,6 @@ def save(self, fp, format=None, **params):
19341934 # may mutate self!
19351935 self .load ()
19361936
1937- save_all = params .pop ('save_all' , False )
1938- self .encoderinfo = params
1939- self .encoderconfig = ()
1940-
19411937 preinit ()
19421938
19431939 ext = os .path .splitext (filename )[1 ].lower ()
@@ -1952,11 +1948,20 @@ def save(self, fp, format=None, **params):
19521948
19531949 if format .upper () not in SAVE :
19541950 init ()
1955- if save_all :
1951+ if params . pop ( ' save_all' , False ) :
19561952 save_handler = SAVE_ALL [format .upper ()]
19571953 else :
19581954 save_handler = SAVE [format .upper ()]
19591955
1956+ if params .get ('convert_mode' ):
1957+ plugin = sys .modules [save_handler .__module__ ]
1958+ converted_im = self ._convert_mode (plugin , params )
1959+ if converted_im :
1960+ return converted_im .save (fp , format , ** params )
1961+
1962+ self .encoderinfo = params
1963+ self .encoderconfig = ()
1964+
19601965 if open_fp :
19611966 if params .get ('append' , False ):
19621967 fp = builtins .open (filename , "r+b" )
@@ -1972,6 +1977,37 @@ def save(self, fp, format=None, **params):
19721977 if open_fp :
19731978 fp .close ()
19741979
1980+ def _convert_mode (self , plugin , params ):
1981+ if not hasattr (plugin , '_convert_mode' ):
1982+ return
1983+ new_mode = plugin ._convert_mode (self )
1984+ if self .mode == 'LA' and new_mode == 'P' :
1985+ alpha = self .getchannel ('A' )
1986+ # Convert the image into P mode but only use 255 colors
1987+ # in the palette out of 256.
1988+ im = self .convert ('L' ) \
1989+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
1990+ # Set all pixel values below 128 to 255, and the rest to 0.
1991+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
1992+ # Paste the color of index 255 and use alpha as a mask.
1993+ im .paste (255 , mask )
1994+ # The transparency index is 255.
1995+ im .info ['transparency' ] = 255
1996+ return im
1997+
1998+ elif self .mode == 'I' :
1999+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
2000+ return im .convert (new_mode ) if new_mode != 'L' else im
2001+
2002+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
2003+ fill_color = params .get ('fill_color' , 'white' )
2004+ background = new (new_mode , self .size , fill_color )
2005+ background .paste (self , self .getchannel ('A' ))
2006+ return background
2007+
2008+ elif new_mode :
2009+ return self .convert (new_mode )
2010+
19752011 def seek (self , frame ):
19762012 """
19772013 Seeks to the given frame in this sequence file. If you seek
0 commit comments