Embedded_game/JTBZ/调整图片.py

43 lines
1.3 KiB
Python
Raw Normal View History

2025-01-02 12:48:11 +08:00
# -*- coding:utf-8 -*-
# @Author len
# @Create 2023/11/9 15:21
from PIL import Image, ImageOps
def resize_image(image_path, target_width, target_height, fill_color):
# 打开图像
image = Image.open(image_path)
# 创建一个新的空白图像
new_image = Image.new("RGB", (target_width, target_height), fill_color)
# 计算调整后图像的大小和位置
width, height = image.size
ratio = min(target_width / width, target_height / height)
new_width = int(width * ratio)
new_height = int(height * ratio)
x = (target_width - new_width) // 2
y = (target_height - new_height) // 2
# 调整图像大小并粘贴到新图像上
resized_image = image.resize((new_width, new_height), resample=Image.Resampling.LANCZOS)
new_image.paste(resized_image, (x, y))
# 返回调整后的图像
return new_image
if __name__ == "__main__":
# 输入图像路径
image_path = "frame_40.jpg"
# 目标宽度和高度
target_width = 800
target_height = 480
# 填充颜色
fill_color = (255, 255, 255) # 白色
# 调整图像大小并进行边缘填充
resized_image = resize_image(image_path, target_width, target_height, fill_color)
# 保存调整后的图像
resized_image.save("output.jpg")