code: def flatten(image, bgcolor=None):
          
          if bgcolor:
              background = PIL.Image.new('RGB', image.size, bgcolor)
              background.paste(image, mask=image.split()[3])
              return background
  
          return image.convert('RGB')
docs: Flatten an image, with an optional background color