问题描述
foreground.png
background1.png
background2.png
解决方案
- 找出面积较大图片,等待缩小
- 比较宽优先和高优先的面积
- 调整高或宽
from PIL import Image
def match_size(image1, image2):
'''匹配两图,根据面积返回等比调整宽高后的两图'''
(width1, height1), (width2, height2) = image1.size, image2.size
area1, area2 = width1 * height1, width2 * height2
width, height, large = (width1, height1, image2) if area1 < area2 else (width2, height2, image1) # 调整大图
_width, _height = large.size # 大图宽高
area_width, area_height = _width * height, _height * width # 宽优先和高优先面积
_width, _height = (width, width / _width * _height) if area_width > area_height else (
height / _height * _width, height)
size = (int(_width), int(_height))
image1, image2 = (image1, image2.resize(size)) if area1 < area2 else (image1.resize(size), image2) # 调整尺寸
return image1, image2
background1 = Image.open('background1.png') # 背景图1
background2 = Image.open('background2.png') # 背景图2
foreground = Image.open('foreground.png') # 前景图
background1, foreground = match_size(background1, foreground)
background2, foreground = match_size(background2, foreground)
print(foreground.size, background1.size, background2.size)
# (400, 400) (400, 307) (307, 400)