Skip to content

Instantly share code, notes, and snippets.

@Jwely
Created May 20, 2016 17:56
Show Gist options
  • Save Jwely/42a6726580e007349abf853ace882866 to your computer and use it in GitHub Desktop.
Save Jwely/42a6726580e007349abf853ace882866 to your computer and use it in GitHub Desktop.
Small script that "flattens" transparent png files by setting the alpha layer to a color.
from PIL import Image
class AmbiguousArgs(BaseException):
pass
def remove_png_alpha(image_path, overwrite=False, color=(255, 255, 255), out_path=None):
"""
Removes the alpha layer form an input png (probably works with other filetypes as well)
"""
if out_path is None and overwrite is True:
out_path = image_path
elif overwrite is False and out_path is None:
raise AmbiguousArgs("If overwrite is false, must input out_path argument!")
with Image.open(image_path).convert("RGBA") as png:
background = Image.new("RGBA", png.size, color)
alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save(out_path)
return alpha_composite
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment