Embedded_game/模块一/000_png_to_bmp.py

38 lines
1.3 KiB
Python
Raw Normal View History

2025-01-02 12:48:11 +08:00
# -*- coding: utf-8 -*-
# @Time : 2024/2/8 19:15
# @Author : len
# @File : 000_png_to_bmp.py
# @Software: PyCharm
# @Comment :
import os
from PIL import Image
# 定义PNG图片所在的文件夹路径
png_images_folder = r'D:\Code\Python\Embedded_game\模块一\img'
# 定义BMP图片保存的文件夹路径
bmp_images_folder = r'D:\Code\Python\Embedded_game\模块一\img_old'
# 确保BMP保存的文件夹存在
os.makedirs(bmp_images_folder, exist_ok=True)
# 获取该文件夹内所有PNG文件的路径
png_files = [os.path.join(png_images_folder, f) for f in os.listdir(png_images_folder) if f.endswith('.png')]
# 为每个PNG文件创建一个对应的BMP文件路径
bmp_files = [os.path.join(bmp_images_folder, os.path.basename(f).replace('.png', '.bmp')) for f in png_files]
# 批量转换PNG到BMP
for png, bmp in zip(png_files, bmp_files):
with Image.open(png) as img:
# 如果PNG图片有alpha通道移除它
if 'A' in img.getbands():
# 创建一个白色背景的Image对象
bg = Image.new("RGB", img.size, (255, 255, 255))
# 粘贴原始图像到背景上忽略alpha通道
bg.paste(img, mask=img.split()[3])
img = bg
img.save(bmp, 'BMP')
print(f"图片 '{png}' 已转换为BMP格式并保存为 '{bmp}'")