@@ -1909,12 +1909,6 @@ def save(self, fp, format=None, **params):
19091909 # may mutate self!
19101910 self .load ()
19111911
1912- save_all = False
1913- if 'save_all' in params :
1914- save_all = params .pop ('save_all' )
1915- self .encoderinfo = params
1916- self .encoderconfig = ()
1917-
19181912 preinit ()
19191913
19201914 ext = os .path .splitext (filename )[1 ].lower ()
@@ -1929,11 +1923,23 @@ def save(self, fp, format=None, **params):
19291923
19301924 if format .upper () not in SAVE :
19311925 init ()
1926+ save_all = False
1927+ if 'save_all' in params :
1928+ save_all = params .pop ('save_all' )
19321929 if save_all :
19331930 save_handler = SAVE_ALL [format .upper ()]
19341931 else :
19351932 save_handler = SAVE [format .upper ()]
19361933
1934+ if params .get ('convert_mode' ):
1935+ plugin = sys .modules [save_handler .__module__ ]
1936+ convertedIm = self ._convert_mode (plugin , params )
1937+ if convertedIm :
1938+ return convertedIm .save (fp , format , ** params )
1939+
1940+ self .encoderinfo = params
1941+ self .encoderconfig = ()
1942+
19371943 if open_fp :
19381944 if params .get ('append' , False ):
19391945 fp = builtins .open (filename , "r+b" )
@@ -1949,6 +1955,37 @@ def save(self, fp, format=None, **params):
19491955 if open_fp :
19501956 fp .close ()
19511957
1958+ def _convert_mode (self , plugin , params ):
1959+ if not hasattr (plugin , '_convert_mode' ):
1960+ return
1961+ new_mode = plugin ._convert_mode (self )
1962+ if self .mode == 'LA' and new_mode == 'P' :
1963+ alpha = self .getchannel ('A' )
1964+ # Convert the image into P mode but only use 255 colors
1965+ # in the palette out of 256.
1966+ im = self .convert ('L' ) \
1967+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
1968+ # Set all pixel values below 128 to 255, and the rest to 0.
1969+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
1970+ # Paste the color of index 255 and use alpha as a mask.
1971+ im .paste (255 , mask )
1972+ # The transparency index is 255.
1973+ im .info ['transparency' ] = 255
1974+ return im
1975+
1976+ elif self .mode == 'I' :
1977+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
1978+ return im .convert (new_mode ) if new_mode != 'L' else im
1979+
1980+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
1981+ fill_color = params .get ('fill_color' , 'white' )
1982+ background = new (new_mode , self .size , fill_color )
1983+ background .paste (self , self .getchannel ('A' ))
1984+ return background
1985+
1986+ elif new_mode :
1987+ return self .convert (new_mode )
1988+
19521989 def seek (self , frame ):
19531990 """
19541991 Seeks to the given frame in this sequence file. If you seek
0 commit comments