示例代码使用Python 的PIL和Tkinter库。根据屏幕大小按照原图片长宽比例进行无拉伸的等比例缩放。预设屏幕方向为竖屏(1080 * 4096),仅是为了适应手机图片。图片缩放比例对照原图的长宽比例,分多次进行,包含快速调整、精确微调以及适应性调整。
# ...
from PIL import Image, ImageTk
# ...
# 预设竖屏图片尺寸
I_WIDTH = 1080
I_HEIGHT = 4096
def image_resize(path, screen_width=0, screen_height=0):
image = Image.open(path)
if screen_width <= 0:
screen_width = I_WIDTH
if screen_height <= 0:
screen_height = I_HEIGHT
raw_width, raw_height = image.size[0], image.size[1]
max_width, max_height = raw_width, screen_height
min_width = max(raw_width, max_width)
# 按照比例缩放
min_height = int(raw_height * min_width / raw_width)
# 第1次快速调整
while min_height > screen_height:
min_height = int(min_height * .9533)
# 第2次精确微调
while min_height < screen_height:
min_height += 1
# 按照比例缩放
min_width = int(raw_width * min_height / raw_height)
# 适应性调整
while min_width > screen_width:
min_width -= 1
# 按照比例缩放
min_height = int(raw_height * min_width / raw_width)
return image.resize((min_width, min_height))