Python USES pil to fill a PNG image with background color

  • 2020-04-02 14:41:04
  • OfStack

This example shows how python USES pil to fill a PNG image with background color. Share with you for your reference. Specific analysis is as follows:

Some PNG images have no background color. If you want to fill the background with a single color (such as white), you can use the following code, which fills the jb51.net.png image in the current directory with a white background.

Use the background color of the specified color, and then fill the image with an alpha channel on the monochrome background.  
For example, use a white background below:


im = Image.open('jb51.net.png')
x,y = im.size 
try: 
  #  Use white to fill the background  from : www.jb51.net
  # (alpha band as paste mask). 
  p = Image.new('RGBA', im.size, (255,255,255))
  p.paste(im, (0, 0, x, y), im)
  p.save('jb51.net.png')
except:
  pass

I hope this article has helped you with your Python programming.


Related articles: