Create a PNG and make it transparent

Question:

I’m trying to dynamically create a PNG (code is working) and make it transparent (code is not working on the color white).

I can create the PNG, but making it transparent isn’t working.

Code:

from PIL import Image, ImageDraw, ImageFont
import os

def text_on_img(filename='01.png', text="Hello", size=12):
    "Draw a text on an Image, saves it, show it"
    fnt = ImageFont.truetype('arial.ttf', 52)
    # create image
    image = Image.new(mode="RGB", size=(150, 75), color="white")
    draw = ImageDraw.Draw(image)
    # draw text
    draw.text((10, 10), text, font=fnt, fill=(0, 0, 0))
    newData = []
    newData.append((255, 255, 255, 0))

    image.save(filename)
Asked By: Joe

||

Answers:

Here’s a minimal example that creates the image in RGBA mode and sets the background to be transparent.

from PIL import Image, ImageDraw, ImageFont
fnt = ImageFont.truetype("arial.ttf", 52)
img = Image.new(mode="RGBA", size=(150, 75), color=(255, 255, 255, 127))
draw = ImageDraw.Draw(img)
draw.text((10, 10), "Hello", font=fnt, fill=(0, 0, 0))
img.save("test.png", "PNG")

This creates the following image:

Hello, fully transparent background

Changing the alpha to 127 (50%) results in the following image being created:

Hello, 50% Opacity

Answered By: import random
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.