调整图像大小并使其适合画布尺寸

问题描述 投票:0回答:2

任何人都可以帮我使用 ImageTk 调整图像大小吗?

我有一块画布,我会把照片放在那里。

我有不同种类的图片=所有图片的尺寸不同

当我将图片(仅一张)附加到画布中时,我希望调整图片的大小,以便它适合画布并且仍保持其比例。

请帮助我!我是 PIL、Tkinter 和 Python 的新手。

更新:

我尝试在

thumbnail
下使用
Image
,但在调整大小时:

self.image.thumbnail(self.picsize,Image.ANTIALIAS)

图像不适合画布尺寸,如果图像比画布长/宽,则仅将其剪切。 (不调整大小以适合画布)


代码:

from PIL import ImageTk
from Tkinter import *
import os,tkFileDialog,Image

picsize = 250,250 # I want to set this so that it will fit in the self.imagecanvas | Every images attached will share same Size
imagepath = "Default_ProPic.jpg"
class GUI():
    global picsize
    def display(self):
        self.canvas = Canvas(width=1200,height=700)
        self.canvas.pack()
    
        self.imagecanvas = Canvas(self.canvas,width=400,height=400)
        self.imagecanvas.place(x=980,y=180)
        self.image = Image.open(imagepath)
        self.image.thumbnail(picsize,Image.ANTIALIAS)
        self.newimage = ImageTk.PhotoImage(self.image)
        self.profile_picture=self.imagecanvas.create_image(0,0,anchor = NW,image=self.newimage)
    
        attachbutton = Button(self.canvas,text="       Profile Pic       ",command=lambda:self.attachpic())
        attachbutton.place(x=1030,y=320)
    
        mainloop()

    def attachpic(self):
        global picsize
        attachphoto = tkFileDialog.askopenfilename(title="Attach photo")
        self.image = Image.open(attachphoto)
        self.image.thumbnail(picsize,Image.ANTIALIAS)
        self.newimage = ImageTk.PhotoImage(self.image)
        self.imagecanvas.itemconfigure(self.profile_picture, image=self.newimage)
    
GUI = GUI()
GUI.display()

上面使用的图片:enter image description here

python python-2.7 tkinter python-imaging-library
2个回答
0
投票

尝试将缩略图保存为单独的变量:

self.thmb_img = self.image.thumbnail(picsize, Image.ANTIALIAS)

我怀疑它可能会拿走原版

self.image = Image.open(attachphoto)

我建议观察尺码情况:

def attachpic(self):
    picsize = 250, 250
    attachphoto = tkFileDialog.askopenfilename(title="Attach photo")
    self.image = Image.open(attachphoto)
    print self.image.size()
    self.thmb_img = self.image.thumbnail(picsize,Image.ANTIALIAS)
    print self.thmb_img.size()

检查输出尺寸并验证其与原始尺寸和所需的 (250, 250) 缩略图相同。


0
投票

您需要做的就是弄清楚应该调整到的尺寸

  • 使其全部适合窗口,并且
  • 保留原始纵横比。

幸运的是,这并不难做到。

 def best_fit(oldsize, picsize):
    new_width, new_height = picsize
    old_width, old_height = oldsize
    # if new_width/old_width < new_height/old_height is mathematically the same as
    if new_width * old_height < new_height * old_width:
        # reduce height to keep original aspect ratio
        new_height = max(1, old_height * new_width // old_width)
    else:
        # reduce width to keep original aspect ratio
        new_width = max(1, old_width * new_height // old_height)
    return (new_width, new_height)

siz = self.image.size
self.image = self.image.resize(best_fit(siz, picsize), Image.ANTIALIAS)

max
调用可防止宽度和高度为零。

© www.soinside.com 2019 - 2024. All rights reserved.