pythonpython-imaging-libraryreplit

image background turns black on python pillow


ive been trying to make a chess bot using pillow and discord.py, but when i try to paste a png photo with no background it replace the background to black

ps: you need to write pip install pillow in the terminal/shell to use the code

from PIL import Image, ImageDraw
img = Image.new(mode="RGB", size=(410, 410), color="white")

black_rook = Image.open("black_rook.png")

currect_image = black_rook

img.paste(currect_image, (50, 50))

img.save("test.jpg")

the rook image file board image

if you want to check this its currectly on replit, my account name is shomshom37 and the project is "Game_hub_bot1.0", heres a link: https://replit.com/@shomshom375573

i expected the image to be pasted without the background, insted it added the background to the picture


Solution

  • You need to use the alpha channel of the image as the mask when pasting, like this:

    img.paste(currect_image, (50, 50), currect_image)
    

    Otherwise all the pixels of the background image are affected, rather than only those where the pasted image is opaque.