Record a PIL method to convert a transparent background to a white background

The first article searched on Baidu can indeed convert a transparent background to a white background, but the defect is very serious, which will cause a lot of pixels in the background of the picture, and the efficiency is not very high.

After another search, I found a better way .

from PIL import Image

try:
    imagePtah = 'your image file path'
    img = Image.open(imagePtah)
    if img.mode != 'RGBA':
        image = img.convert('RGBA')
    width = img.width
    height = img.height

    image = Image.new('RGB', size=(width, height), color=(255, 255, 255))
    image.paste(img, (0, 0), mask=img)

    image.show()
    
except Exception as e:
    print(e)

Use Image.pasteis so simple and so. Baidu's life is black.
The above method, of course, can also be converted to other colors, just choose the one you need, just replace color=(255, 255, 255)it.

Guess you like

Origin blog.csdn.net/Ser_Bad/article/details/106762611