一个Python脚本,删除原图片白色背景并输出正方形的PNG

重复工作还是用python来解决比较好

#python process_img.py

from PIL import Image, ImageOps
import os

def remove_white_background(image):
    # 将图像转换为 RGBA 模式(如果尚未)
    image = image.convert("RGBA")
    datas = image.getdata()
    
    # 创建一个新的透明图像
    new_data = []
    for item in datas:
        # 设置白色背景的透明像素
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            new_data.append((255, 255, 255, 0))
        else:
            new_data.append(item)
    
    image.putdata(new_data)
    return image

def process_image(input_path, output_dir, target_size=(1920, 1920), background_color=(255, 255, 255, 0)):
    # 如果输出目录不存在,则创建它
    os.makedirs(output_dir, exist_ok=True)
    
    # 打开输入图像
    with Image.open(input_path) as image:
        # 移除白色背景
        image = remove_white_background(image)
        
        # 创建一个新图像,具有所需的大小和背景颜色
        new_image = Image.new("RGBA", target_size, background_color)
        
        # 在保持长宽比的同时调整图像大小
        image.thumbnail((target_size[0] * 1, target_size[1] * 1), Image.LANCZOS)
        
        # 计算将调整大小的图像粘贴到新图像上的位置
        position = ((target_size[0] - image.size[0]) // 2, (target_size[1] - image.size[1]) // 2)
        
        # 将调整大小的图像粘贴到新图像上
        new_image.paste(image, position, mask=image)
        
        # 构造 PNG 文件的输出路径
        output_filename = os.path.splitext(os.path.basename(input_path))[0] + ".png"
        output_path = os.path.join(output_dir, output_filename)
        
        # 将结果保存为具有透明度的 PNG 图像
        new_image.save(output_path, format="PNG")

def process_directory(input_dir):
    # 处理输入目录中的每个图像文件
    for filename in os.listdir(input_dir):
        if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
            input_path = os.path.join(input_dir, filename)
            process_image(input_path, input_dir)

if __name__ == "__main__":
    while True:
        input_directory = input("请输入要处理的文件夹路径(输入 q 退出):")
        
        if input_directory.lower() == "q":
            break
        
        if not os.path.isdir(input_directory):
            print("错误:输入路径不是一个文件夹。")
            continue
        
        process_directory(input_directory)

 

本文作者:𝙕𝙆𝘾𝙊𝙄

文章名称:一个Python脚本,删除原图片白色背景并输出正方形的PNG

文章链接:https://www.zkcoi.com/365up/program/3227.html

本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
𝙕𝙆𝘾𝙊𝙄𝙕𝙆𝘾𝙊𝙄
上一篇 2024年2月27日
下一篇 2024年3月6日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

私聊博主

立即联系
一般有空就回复

qrcode_web

微信扫码联系我

分享本页
返回顶部