Image resize under PhotoImage

后端 未结 4 778
盖世英雄少女心
盖世英雄少女心 2020-11-29 08:07

I need to resize an image, but I want to avoid PIL, since I cannot make it work under OS X - don\'t ask me why...

Anyway since I am satisfied with gif/pgm/ppm, the P

相关标签:
4条回答
  • 2020-11-29 08:43

    Because both zoom() and subsample() want integer as parameters, I used both.

    I had to resize 320x320 image to 250x250, I ended up with

    imgpath = '/path/to/img.png'
    img = PhotoImage(file=imgpath)
    img = img.zoom(25) #with 250, I ended up running out of memory
    img = img.subsample(32) #mechanically, here it is adjusted to 32 instead of 320
    panel = Label(root, image = img)
    
    0 讨论(0)
  • 2020-11-29 08:52

    You have to either use the subsample() or the zoom() methods of the PhotoImage class. For the first option you first have to calculate the scale factors, simply explained in the following lines:

    scale_w = new_width/old_width
    scale_h = new_height/old_height
    photoImg.zoom(scale_w, scale_h)
    
    0 讨论(0)
  • 2020-11-29 09:04

    If you don't have PIL installed --> install it

    (for Python3+ users --> use 'pip install pillow' in cmd)

    from tkinter import *
    import tkinter
    import tkinter.messagebox
    from PIL import Image
    from PIL import ImageTk
    
    master = Tk()
     
    def callback():
        print("click!")
    
    width = 50
    height = 50
    img = Image.open("dir.png")
    img = img.resize((width,height), Image.ANTIALIAS)
    photoImg =  ImageTk.PhotoImage(img)
    b = Button(master,image=photoImg, command=callback, width=50)
    b.pack()
    mainloop()
    
    0 讨论(0)
  • 2020-11-29 09:06

    I just had the same problem, and I found that @Memes' answer works rather well. Just make sure to reduce your ratio as much as possible, as subsample() takes a rather long time to run for some reason.

    Basically, the image is zoomed out to the least common factor of the two sizes, and then being subsidized by the origonal size. This leaves you with the image of the desired size.

    0 讨论(0)
提交回复
热议问题