Search code examples
pythontkinterpython-imaging-libraryimage-resizingantialiasing

Reading an image from a URL, resizing it and applying antialiasing


I'm trying to resize and apply antialiasing to an image I previously displayed in Tkinter. I'm reading it from a url. The problem is, I opened the image with tkinter.PhotoImage, and the resize() function I need is in PIL.Image. I'd like to know if there's a way to convert from one to another, or some other way I can resolve this issue.

Here's the code:

import tkinter
from urllib.request import urlopen
import base64
from PIL import Image

window = tkinter.Tk()

url = "https://s.yimg.com/os/weather/1.0.1/shadow_icon/60x60/[email protected]"
b64_data = base64.encodestring(urlopen(url).read())
image = tkinter.PhotoImage(data=b64_data)

# Function I need:
#image = image.resize((100, 100), Image.ANTIALIAS)

label = tkinter.Label(image=image)
label.pack()

window.mainloop()

If there's a completely different way I can achieve this, I'd like to hear it.


Solution

  • Ok, well you first use PIL and then use PIL's TKinter Format to convert it to a TKinter Image. I don't have the urllib on my system so I've used Requests, but that part should be exchangeable.

    import tkinter
    import base64
    from PIL import Image, ImageTk
    
    import requests
    from PIL import Image
    from StringIO import StringIO
    url = "https://s.yimg.com/os/weather/1.0.1/shadow_icon/60x60/[email protected]"
    r = requests.get(url)
    pilImage = Image.open(StringIO(r.content))
    pilImage.resize((100, 100), Image.ANTIALIAS)
    
    window = tkinter.Tk()
    
    
    image = ImageTk.PhotoImage(pilImage)
    
    label = tkinter.Label(image=image)
    label.pack()
    
    window.mainloop()
    

    There is one whole page dedicated for PIL and Tkinter: http://effbot.org/tkinterbook/photoimage.htm