是否有任何方法可以为用户提供一个选项,以便在将其上载到我的tkinter fyi窗口之前调整其图像大小

问题描述 投票:-1回答:1

我正在与Instagram的个人资料页类似的项目(tkinter-python)中工作,并且已向用户提供了一个功能,供用户选择需要上传到窗口的图像,但我希望图像的大小要上传的文件应小于特定大小。我应该怎么做才能为用户提供在上传之前调整图像大小的选项?

from tkinter import *
from PIL import Image,ImageTk
import tkinter.messagebox as tmsg
#Profile Photo
image=Image.open(f"{name}.jpg")
width,height=image.size
area=width*height
if area<=160012:
  photo=ImageTk.Photoimage(image)
  Label(image=photo).place(X=1000,y=2)
else:
  tmsg.showinfo('Crop image','WIDTH X HEIGHT must be smaller than 160012')
python image tkinter python-imaging-library crop
1个回答
0
投票

您可以为用户调整图像大小:

from tkinter import *
from PIL import Image,ImageTk

MAX_AREA = 160012

#Profile Photo
name = 'path/to/user/profile/image'
image = Image.open(f"{name}.jpg")
width, height = image.size
area = width * height

if area > MAX_AREA:
    # determine the resize ratio
    ratio = (MAX_AREA / area) ** 0.5
    # calculate the resized width and height
    new_w = int(width * ratio)
    new_h = int(height * ratio)
    # resize the image
    image = image.resize((new_w, new_h))
    print(f'Image is resized from {width}x{height} ({area}) to {new_w}x{new_h} ({new_w*new_h})')

root = Tk()
root.geometry('1000x600')
photo = ImageTk.PhotoImage(image)
Label(image=photo).place(x=1000, y=0, anchor='ne')
root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.