@@ -1903,12 +1903,6 @@ def save(self, fp, format=None, **params):
19031903 # may mutate self!
19041904 self .load ()
19051905
1906- save_all = False
1907- if 'save_all' in params :
1908- save_all = params .pop ('save_all' )
1909- self .encoderinfo = params
1910- self .encoderconfig = ()
1911-
19121906 preinit ()
19131907
19141908 ext = os .path .splitext (filename )[1 ].lower ()
@@ -1923,11 +1917,23 @@ def save(self, fp, format=None, **params):
19231917
19241918 if format .upper () not in SAVE :
19251919 init ()
1920+ save_all = False
1921+ if 'save_all' in params :
1922+ save_all = params .pop ('save_all' )
19261923 if save_all :
19271924 save_handler = SAVE_ALL [format .upper ()]
19281925 else :
19291926 save_handler = SAVE [format .upper ()]
19301927
1928+ if params .get ('convert_mode' ):
1929+ plugin = sys .modules [save_handler .__module__ ]
1930+ convertedIm = self ._convert_mode (plugin , params )
1931+ if convertedIm :
1932+ return convertedIm .save (fp , format , ** params )
1933+
1934+ self .encoderinfo = params
1935+ self .encoderconfig = ()
1936+
19311937 if open_fp :
19321938 if params .get ('append' , False ):
19331939 fp = builtins .open (filename , "r+b" )
@@ -1943,6 +1949,37 @@ def save(self, fp, format=None, **params):
19431949 if open_fp :
19441950 fp .close ()
19451951
1952+ def _convert_mode (self , plugin , params ):
1953+ if not hasattr (plugin , '_convert_mode' ):
1954+ return
1955+ new_mode = plugin ._convert_mode (self )
1956+ if self .mode == 'LA' and new_mode == 'P' :
1957+ alpha = self .getchannel ('A' )
1958+ # Convert the image into P mode but only use 255 colors
1959+ # in the palette out of 256.
1960+ im = self .convert ('L' ) \
1961+ .convert ('P' , palette = ADAPTIVE , colors = 255 )
1962+ # Set all pixel values below 128 to 255, and the rest to 0.
1963+ mask = eval (alpha , lambda px : 255 if px < 128 else 0 )
1964+ # Paste the color of index 255 and use alpha as a mask.
1965+ im .paste (255 , mask )
1966+ # The transparency index is 255.
1967+ im .info ['transparency' ] = 255
1968+ return im
1969+
1970+ elif self .mode == 'I' :
1971+ im = self .point ([i // 256 for i in range (65536 )], 'L' )
1972+ return im .convert (new_mode ) if new_mode != 'L' else im
1973+
1974+ elif self .mode in ('RGBA' , 'LA' ) and new_mode in ('RGB' , 'L' ):
1975+ fill_color = params .get ('fill_color' , 'white' )
1976+ background = new (new_mode , self .size , fill_color )
1977+ background .paste (self , self .getchannel ('A' ))
1978+ return background
1979+
1980+ elif new_mode :
1981+ return self .convert (new_mode )
1982+
19461983 def seek (self , frame ):
19471984 """
19481985 Seeks to the given frame in this sequence file. If you seek
0 commit comments