Adding Background Color to PNG using Python

Adding Background Color to PNG using Python

Reference

Dependency

python 3.7.2

pytesseract

pip install pytesseract

The Code

from PIL import Image
im = Image.open(r"C:\tmp\test.png")

fill_color = (120,8,220)  # your new background color

im = im.convert("RGBA")   # it had mode P after DL it from OP
if im.mode in ('RGBA', 'LA'):
    background = Image.new(im.mode[:-1], im.size, fill_color)
    background.paste(im, im.split()[-1]) # omit transparency
    im = background

im.convert("RGB").save(r"C:\tmp\result.jpg")

Loop Through Folder

import os
from PIL import Image

path = r"C:\tmp"

for root, dirs, files in os.walk(path, topdown=False):
    for name in files:
        print(os.path.join(root, name))

        im = Image.open(os.path.join(root, name))

        fill_color = (120,8,220)   # your new background color

        im = im.convert("RGBA")   # it had mode P after DL it from OP
        if im.mode in ('RGBA', 'LA'):
            background = Image.new(im.mode[:-1], im.size, fill_color)
            background.paste(im, im.split()[-1]) # omit transparency
            im = background
        result = name.replace(".png", ".jpg")

        im.convert("RGB").save(os.path.join(root, result))
Show Comments