Python + PIL + Tkinter: 图片原比例缩放

98 篇文章 1 订阅

示例代码使用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))

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要根据窗体大小自动缩放显示图像,你可以使用 `PIL` 库来加载图像,并使用 `tkinter` 中的 `Label` 组件来显示图像。然后,你可以使用 `bind` 方法来绑定窗体大小变化事件,以更新图像的大小和位置。 下面是一个示例程序,它可以在窗体大小变化时自动缩放显示图像: ```python import tkinter as tk from PIL import Image, ImageTk class App: def __init__(self, master): self.master = master self.master.title("自动缩放图像") self.master.geometry("400x400") self.image = Image.open("image.jpg") self.photo = ImageTk.PhotoImage(self.image) self.label = tk.Label(self.master, image=self.photo) self.label.pack(fill=tk.BOTH, expand=True) self.master.bind("<Configure>", self.on_resize) def on_resize(self, event): w, h = event.width, event.height self.image = self.image.resize((w, h)) self.photo = ImageTk.PhotoImage(self.image) self.label.config(image=self.photo) if __name__ == "__main__": root = tk.Tk() app = App(root) root.mainloop() ``` 在上面的程序中,我们首先创建了一个 `Image` 对象,然后使用它创建了一个 `PhotoImage` 对象,这个对象可以被 `Label` 组件用来显示图像。接着,我们创建了一个 `Label` 组件,并将 `PhotoImage` 对象作为参数传递给它。我们还使用了 `pack` 方法来将 `Label` 组件放置在窗口中心,并设置了 `fill` 和 `expand` 参数,以使其自动填充和扩展窗口。 最后,我们使用 `bind` 方法来绑定 `<Configure>` 事件,这个事件会在窗口大小变化时触发。我们在事件处理程序中,获取窗口的新大小,然后使用 `resize` 方法来缩放图像,使其适应新的窗口大小。接着,我们使用 `PhotoImage` 对象来创建一个新的 `Label` 对象,并将其作为参数传递给 `config` 方法,以更新图像的大小和位置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值