How can I set the background of a transparent imag

2019-07-02 22:01发布

I have a PNG image with transparent background and I want to resize it to another image, but with a white background instead of a transparent one. How can I do that with PIL?

Here is my code:

basewidth = 200
img = Image.open("old.png")
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)hsize = int((float(img.size[1]) * float(wpercent)))
img.save("new.png")

2条回答
劫难
2楼-- · 2019-07-02 22:43
import Image
from resizeimage import resizeimage

f = Image.open('old.png') 
alpha1 = 0 # Original value
r2, g2, b2, alpha2 = 255, 255, 255,255 # Value that we want to replace it with

red, green, blue,alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]
mask = (alpha==alpha1)
data[:,:,:3][mask] = [r2, g2, b2, alpha2]

data = np.array(f)
f = Image.fromarray(data)
f = f.resize((basewidth,hsize), PIL.Image.ANTIALIAS)

f.save('modified.png', image.format)
查看更多
唯我独甜
3楼-- · 2019-07-02 22:48

You can check whether the alpha channel is set to less than 255 on each pixel (which means that it is not opaque) and then set it to white and opaque.

It might not be an ideal solution if you have transparency in other parts of your image, besides the background.

...
pixels = img.load()

for y in xrange(img.size[1]): 
    for x in xrange(img.size[0]): 
        if pixels[x,y][3] < 255:    # check alpha
            pixels[x,y] = (255, 255, 255, 255)
img.save("new.png") 
查看更多
登录 后发表回答