我想叠加两张图片,其中一张是透明的

时间:2019-07-02 16:43:08

标签: python image render

我要叠加两张图片,因为他们知道其中一张已经是透明的!

我在网上浏览了一下已完成的操作,这是我发现并适应的:

IllegalArgumentException: Empty name segment is not allowed for module

AND

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")

我的透明图像放置在其他图像的前面,但是透明部分变成了绿色,因此隐藏了其他图像

我该如何解决?

1 个答案:

答案 0 :(得分:0)

经过很多麻烦,我终于做到了! (我为接下来要为此奋斗的家伙们写了它!)

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

from PIL import Image

def transparent_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 superposer_img(ft,bg):#ft =正面,bg =背景

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")