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:

image-20210319135928724

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
    └── generate_png_transparent_demo.py

Explain as follows:

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

3.2 The function

Here is the core function in generate_png_transparent_demo.py:

from PIL import Image,ImageDraw

# define the size of the image
DEFAULT_WIDTH = 200
DEFAULT_HEIGHT = 80

# 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 = Image.new("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
    img.save(image_file_name,'PNG')
    img.show(image_file_name)
    pass

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 generate_png_transparent_demo.py

We get this:

image-20210319141750976

It works!

5. Summary

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

-->