Search code examples
python-3.xpython-imaging-librarymask

Mask Won't Stay After Converting Image


I'm having trouble with masking a .png image and then converting that image to RGB. I'm doing this to make the mask effect more visible on a white background.

I've done the .convert('RGB') method before saving, and pasting the masked image onto a newly created white image. Both have no effect on the starting image:

from PIL import Image
import os

path = os.path.dirname(os.path.realpath(__file__)) + '/'

mask = Image.open(path + "snap_mask.png")
mask = mask.convert("L")
im = Image.open(path + "snap.png")
im.putalpha(mask)

im.convert('RGB').save(path + "snap_output.png")

The starting image and the final result end up being the same. Here are the links to the images I'm using (it's for a discord bot):

snap.png (right side of image is grey so particle effect can be seen)

snap_mask.png

snap_output.png

desired_output (the output I want)

Any help would be greatly appreciated! :-)


Solution

  • So after taking a short break, I realized what I was doing wrong. Instead of converting the image to RGB, I resorted to adding a white image behind the mask. I was doing the .paste() method improperly before, and was able to get the desired final output:

    from PIL import Image
    import os
    
    path = os.path.dirname(os.path.realpath(__file__)) + '/'
    
    mask = Image.open(path + "snap_mask.png")
    mask = mask.convert("L")
    dst_im = Image.open(path + "snap.png")
    dst_im.putalpha(mask)
    
    white = Image.new('RGB', dst_im.size, (255, 255, 255))
    white.paste(dst_im, dst_im)
    
    white.save(path + "snap_output.png")