python-how to create an image with transparent background using python?

1. Purpose

In this post, I would demo how to create an image that has a transparent background, just as follows:


2. The Environment

  • Python 3

3. The code

3.1 The project directory structure

Our working directory name is myscript, this is the structure of it:

└── myscripts/
    ├── images/
    │   ├── readme.txt

Explain as follows:

  • The images directory is a target directory that we would put our result image into it
  • The is the file that do the magic

3.2 The function

Here is the core function in

from PIL import Image,ImageDraw

# define the size of the image

# this function contains three parameters
# 1) image_file_name , the file name to create
# 2) the_text, is the text which would ben drawn on the image
# 3) alpha, the alpha value that control the image background transparency
def generate_png_transparent(image_file_name,the_text,alpha=0):
    # First, we create an image with RGBA mode, the 'A' stands for alpha
    # the last parameter (255,0,0,alpha) means (R,G,B,A), so the image background color is RED
    img ="RGBA",(DEFAULT_WIDTH,DEFAULT_HEIGHT),(255,0,0,alpha))
    # Now we start to draw text on the image
    d = ImageDraw.Draw(img)
    # the text start at position (20,25), and the color is green
    d.text((20,25), the_text, fill=(0, 0, 255))

    # Then we save and show the image,'PNG')

More about alpha value in image:

In digital images, each pixel contains color information (such as values describing intensity of red, green, and blue) and also contains a value for its opacity known as its ‘alphavalue. An alpha value of 1 means totally opaque, and an alpha value of 0 means totally transparent

The details of the code are documented on the code .

3.3 The main function

Now we should provide the user with a main function to start the program:

if __name__ == '__main__':
    generate_png_transparent("./images/a.png","hello world alpha 0",0)
    generate_png_transparent("./images/b.png", "hello world alpha 50", 50)
    generate_png_transparent("./images/c.png", "hello world alpha 100", 100)

3.4 Test the funtion

At last, we can test our watermark function as follows:

 $ python

We get this:


It works!

5. Summary

In this post, we demonstrated how to use python to generate image with transparent background. Thanks for your reading. Regards.