55 lines
2.0 KiB
Python
55 lines
2.0 KiB
Python
|
# -*- coding:utf-8 -*-
|
|||
|
# @Author len
|
|||
|
# @Create 2023/12/11 17:22
|
|||
|
|
|||
|
# 使用中文注释的优化代码
|
|||
|
|
|||
|
from PIL import Image
|
|||
|
|
|||
|
|
|||
|
def resize_image_proportionally(img, target_width, target_height):
|
|||
|
"""按比例缩放图像。"""
|
|||
|
# 计算宽高比并确定新尺寸
|
|||
|
original_width, original_height = img.size
|
|||
|
ratio = min(target_width / original_width, target_height / original_height)
|
|||
|
new_dimensions = (int(original_width * ratio), int(original_height * ratio))
|
|||
|
# 使用 Resampling.LANCZOS 而不是 ANTIALIAS
|
|||
|
return img.resize(new_dimensions, Image.Resampling.LANCZOS)
|
|||
|
|
|||
|
|
|||
|
# 使用修改后的函数来处理图像并生成A4纸拼贴
|
|||
|
def create_a4_collage_proportionally(images_paths, output_path):
|
|||
|
a4_size = (2480, 3508)
|
|||
|
"""在A4纸大小的图像上创建图像拼贴,同时保持它们的宽高比,并且可以指定图像向下和向两边的偏移量。"""
|
|||
|
# 创建一个空白的A4图像
|
|||
|
a4_image = Image.new('RGB', a4_size, "white")
|
|||
|
|
|||
|
# 计算目标尺寸(A4尺寸的一半)
|
|||
|
target_width = (a4_size[0]-900) // 2
|
|||
|
target_height = a4_size[1] // 2
|
|||
|
|
|||
|
|
|||
|
# 处理并粘贴每张图像
|
|||
|
for idx, image_path in enumerate(images_paths):
|
|||
|
with Image.open(image_path) as img:
|
|||
|
# 按比例缩放图像
|
|||
|
resized_img = resize_image_proportionally(img, target_width, target_height)
|
|||
|
|
|||
|
# 计算粘贴位置,将图像向下移动 offset_y 像素,并在水平方向上增加 offset_x
|
|||
|
x_position = (idx % 2) * target_width + 450
|
|||
|
y_position = (idx // 2) * target_height + 600
|
|||
|
|
|||
|
# 将缩放后的图像粘贴到A4背景上
|
|||
|
a4_image.paste(resized_img, (x_position, y_position))
|
|||
|
print(idx, x_position)
|
|||
|
# 将最终的拼贴图保存到文件
|
|||
|
a4_image.save(output_path)
|
|||
|
|
|||
|
# 示例用法
|
|||
|
images = ['data/赛题二任务九2-1.png', 'data/赛题二任务九2-2.png']
|
|||
|
output_path = 'data/赛题二任务九2.png' # 输出路径
|
|||
|
|
|||
|
|
|||
|
# 调用函数创建拼贴图像
|
|||
|
create_a4_collage_proportionally(images, output_path)
|