使它变成透明的PNG

使它变成透明的PNG

本文介绍了Python PIL删除了单词,使它变成透明的PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以用python pil剪切文本并使其透明.这是一个更好地解释它的示例.图片1.png是一个圆圈.

I would like to know if its possible with python pil to cut text out and make the picture transparent. Here is an example to explain it better. Picture 1.png is a circle.

图片2.png是text.png,只表示感谢.我想做的是将picture2放入picture1中,然后将其切出,使其变得透明.所以看起来应该像picture3.png

Picture 2.png is text.png that just says thanks. What I would like to do is put picture2 into picture1 and cut that out so it becomes transparent. so it should look like this picture3.png

到目前为止,这只是我粘贴的图像.我是PIl的新手.我不确定如何告诉python我想要这样切掉.

This is what I have so far but it only pasting the image. I am new to PIl. I am not sure how to tell python I want this cut out like that.

img = Image.open('picture1.png').convert("RGBA")
bg_w, bg_h = img.size
layer = Image.open('picture2.png').convert("RGBA") # this file is the transparent one
img_w, img_h = layer.size
offset = ((bg_w - img_w)/2, (bg_h - img_h) / 3)
img.paste(layer, offset, mask=layer)
img.save('Picture3.png')

推荐答案

我知道了.答案是这样:

I figured it out. Here is the answer:

from PIL import Image, ImageDraw

img = Image.open('circle.png').convert("RGBA")
layer = Image.open('Thanks.png').convert("RGBA") # this file is the transparent one
img.paste(layer, mask=layer)
img.save('Picture3White.png')


img = Image.open('Picture3White.png')
img = img.convert("RGBA")
datas = img.getdata()

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

img.putdata(newData)
img.save("Transparent.png", "PNG")

这篇关于Python PIL删除了单词,使它变成透明的PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 23:47