from PIL import Image
# 加载PNG图像
image_path = 'path/to/your/image.png'
img = Image.open(image_path)
# 将图像转换为RGBA,以便处理透明度
img = img.convert("RGBA")
# 获取图像数据
datas = img.getdata()
# 创建一个新的图像数据列表
new_data = []
for item in datas:
# 将白色(或接近白色)的像素转换为透明
# 这里将RGB值大于250的认为是白色或接近白色
if item[0] > 250 and item[1] > 250 and item[2] > 250:
# 替换为透明,即RGBA中的A(Alpha通道)设置为0
new_data.append((255, 255, 255, 0))
else:
new_data.append(item)
# 更新图像数据
img.putdata(new_data)
# 保存修改后的图像
output_path = 'path/to/your/output_image.png'
img.save(output_path)
# 显示修改后的图像(可选)
img.show()
python读取png文件并将其中的白色转化为透明色
于 2024-02-26 20:15:45 首次发布