David Janes' Code Weblog

September 18, 2011

Adding alpha levels to images with PIL

code fragments,pil,python,tips · admin · 4:54 am ·

I recently was tasked by a client with replacing a number of images — PNGs with alpha levels, such that parts of the image were transparent — with new pictures. The issue was how to get the exact same alpha level holes in the new images.

Here’s how I did it. I renamed one of the original images “template.png” and assumed that all the source images will the exactly the same size as the template. I then wrote this Python script using the Python Imaging Library.

import sys
import os
import re
import Image

#   Get the template
itemplate = Image.open("template.png")
itemplate.getpixel(( 0, 0 ))
r, g, b, alpha = itemplate.split()

#   Get the JPGs - they must be exactly the same size
for in_file in os.listdir("."):
    if not in_file.endswith(".jpg"):

    isrc = Image.open(in_file)
    if isrc.size != itemplate.size:
    idst = isrc.convert("RGBA")

    idst.save(in_file[:-4] + ".png")


No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress

Switch to our mobile site