python快速实现简单的图片透明化

2023-12-17 05:21:26

整张图片透明化的完整代码如下:

import os
import glob
from PIL import Image

def convert_to_transparent(image_path, output_folder):
    image = Image.open(image_path)
    image = image.convert("RGBA")

    data = image.getdata()

    new_data = []
    for item in data:
        # 将背景颜色(不是透明的像素)替换为透明背景(RGBA值为原始RGB值 + 透明度为0)
        if item[3] != 0:
            new_data.append(item[:3] + (0,))
        else:
            new_data.append(item)

    image.putdata(new_data)
    output_path = os.path.join(output_folder, os.path.basename(image_path))
    image.save(output_path, "PNG")
    print(f"{output_path} 转换完成!")

def convert_folder_images(input_folder, output_folder):
    # 获取文件夹下所有jpg和png格式的图片
    image_paths = glob.glob(os.path.join(input_folder, "*.jpg")) + glob.glob(os.path.join(input_folder, "*.png"))

    for image_path in image_paths:
        convert_to_transparent(image_path, output_folder)

# 使用示例
input_folder = r"E:\img"
output_folder = r"E:\img1"
if not os.path.exists(output_folder):
    os.makedirs(output_folder)
convert_folder_images(input_folder, output_folder)

?对黑色和白色背景进行透明化:

import os
import glob
from PIL import Image

def convert_to_transparent(image_path, output_folder):
    image = Image.open(image_path)
    image = image.convert("RGBA")

    data = image.getdata()

    new_data = []
    for item in data:
        # 将白色和黑色背景替换为透明背景(RGBA值为原始RGB值 + 透明度为0)
        if item[0] == 0 and item[1] == 0 and item[2] == 0:
            new_data.append(item[:3] + (0,))
        elif item[0] == 255 and item[1] == 255 and item[2] == 255:
            new_data.append(item[:3] + (0,))
        else:
            new_data.append(item[:3] + (255,))

    image.putdata(new_data)
    output_path = os.path.join(output_folder, os.path.basename(image_path))
    image.save(output_path, "PNG")
    print(f"{output_path} 转换完成!")

def convert_folder_images(input_folder, output_folder):
    # 获取文件夹下所有jpg和png格式的图片
    image_paths = glob.glob(os.path.join(input_folder, "*.jpg")) + glob.glob(os.path.join(input_folder, "*.png"))

    for image_path in image_paths:
        convert_to_transparent(image_path, output_folder)

# 使用示例
input_folder = r"E:\img"
output_folder = r"E:\img1"
if not os.path.exists(output_folder):
    os.makedirs(output_folder)
convert_folder_images(input_folder, output_folder)

效果:

原始图:

全透明化之后在文件夹中的显示效果:

?背景透明化之后在文件夹中的显示效果:

全透明化后查看图片的显示效果:

背景透明化查看图片的显示效果:

?用做QQ头像的显示效果:

?

?

文章来源:https://blog.csdn.net/qq_38563206/article/details/135039788
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。