我想叠加两个图像,其中一个是transparen

2024-07-04 08:59:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着叠加两个图像,知道其中一个已经是透明的!你知道吗

我在网上查阅了一些已经做过的事情,以下是我发现并适应我的:

from PIL import Image


img = Image.open(fr"D:\Prog\Automatisation\Photo tu preferes quoi\signature\signature_1.png")

background = Image.open(fr"D:\Prog\Automatisation\Photo tu preferes quoi\photo_1\oui_1.png")

background.paste(img, (0, 0), new_img)
background.save('how_to_superimpose_two_images_01.png',"PNG")

以及

from PIL import Image


img = Image.open(fr"D:\Prog\Automatisation\Photo tu preferes quoi\signature\signature_1.png")
new_image = Image.new("RGBA", img.size, "WHITE")

background = Image.open(fr"D:\Prog\Automatisation\Photo tu preferes quoi\photo_1\oui_1.png")

background.paste(img, (0, 0), new_img)
background.save('how_to_superimpose_two_images_01.png',"PNG")

我的透明图像被很好地放置在我的另一个图像的前面,但是透明部分变成了绿色,因此隐藏了另一个图像

我该怎么修?你知道吗


Tags: 图像imageimgnewpngopenfrbackground
1条回答
网友
1楼 · 发布于 2024-07-04 08:59:45

经过一番努力,我终于成功了!(我写这封信是为了下一个为之奋斗的人!)你知道吗

使图像透明的函数:(这里,所有的黑色像素都是透明的,您当然可以在那里更改此值)

from PIL import Image

def透明\u 1(myimage):

img = Image.open(myimage) # ex : fr"D:\Prog\Automatisation\Photo tu preferes quoi\signature\signature_1.png"
img = img.convert("RGBA")
datas = img.getdata()

newData = []
for item in datas:
    if item[0] == 0 and item[1] == 0 and item[2] == 0:
        newData.append((0, 0, 0, 0))
    else:
        newData.append(item)

img.putdata(newData)
img.save("image_transparente.png", "PNG") # ca enregistre l'image dans le même dossier que là où est le code

覆盖两个图像的函数:

from PIL import Image

def SUPERPASER(左,右):#左=前,右=背景

filename = ft
front = Image.open(filename, 'r')
filename1 = bg
background = Image.open(filename1, 'r')
text_img = Image.new('RGBA', background.size , (0, 0, 0, 0))
text_img.paste(background, (0,0))
text_img.paste(front, (0,0), mask=front)
text_img.save("image.png", format="png")

以及调用函数的程序:

import sys 
sys.path.append(fr"D:\Prog\Automatisation\Fonction")

from Superposer_image import superposer_img as supimg
from Image_Transparente import transparent_1 as tr


tr(fr"D:\Prog\Automatisation\Photo tu preferes quoi\signature\signature_1.png")

supimg("image_transparente.png",fr"D:\Prog\Automatisation\Photo tu preferes 
quoi\photo_1\a.png")

相关问题 更多 >

    热门问题