Embedded_game/chexing/生成A4文件.py
2025-01-02 12:48:11 +08:00

56 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding:utf-8 -*-
# @Author len
# @Create 2023/11/13 15:16
import os
from PIL import Image
# 设置图片文件夹路径和输出文件夹路径
images_folder_path = r'D:\Waste\嵌入式\2023年嵌入式系统应用开发赛项—第三模块图像参考示例\2023年嵌入式系统应用开发赛项—第三模块图像参考示例\03-各类车型参考图\车型图片' # 替换成你的图片文件夹路径
output_folder_path = r'D:\Waste\嵌入式\2023年嵌入式系统应用开发赛项—第三模块图像参考示例\2023年嵌入式系统应用开发赛项—第三模块图像参考示例\03-各类车型参考图\A4打印' # 替换成你想要保存输出图片的文件夹路径
# A4纸的标准尺寸以像素为单位以300 DPI为例
a4_width_pixels = 2480
a4_height_pixels = 3508
# 绿色框的位置和尺寸(根据实际情况替换这些值)
box_x = 0 # 绿色框左上角的x坐标
box_y = 15 # 绿色框左上角的y坐标
box_width = 2480 # 绿色框的宽度
box_height = 2100 # 绿色框的高度
# 确保输出文件夹存在
os.makedirs(output_folder_path, exist_ok=True)
# 遍历文件夹中的所有图片
for image_name in os.listdir(images_folder_path):
if image_name.lower().endswith('.png'):
image_path = os.path.join(images_folder_path, image_name)
# 创建一张白色的A4纸背景
a4_image = Image.new('RGB', (a4_width_pixels, a4_height_pixels), 'white')
# 加载PNG图片
picture = Image.open(image_path)
# 确保PNG图片是透明的然后将其放置在A4纸的绿色框位置
if picture.mode in ('RGBA', 'LA') or (picture.mode == 'P' and 'transparency' in picture.info):
# 调整PNG图片的大小以适应绿色框
picture.thumbnail((box_width, box_height), Image.Resampling.LANCZOS)
# 计算居中放置图片的位置
picture_x = box_x + (box_width - picture.width) // 2
picture_y = box_y + (box_height - picture.height) // 2
# 将图片粘贴到A4背景上透明区域使用alpha通道
a4_image.paste(picture, (picture_x, picture_y), picture)
# 构造输出文件的路径
output_image_path = os.path.join(output_folder_path, f'output_{image_name}')
# 保存处理过的图片
a4_image.save(output_image_path)
print("所有图片处理完成!")