2

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/partly_cloudy_night@2x.png"
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.

Phil
  • 67
  • 1
  • 8

2 Answers2

4

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/partly_cloudy_night@2x.png"
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

user1767754
  • 23,311
  • 18
  • 141
  • 164
  • 1
    I edited this code a bit and posted a comment. Thank you very much for helping me. – Phil Nov 22 '17 at 19:58
2

I edited @user1767754 code since I had some problems with it, but it did help me greatly.

Note: I used BytesIO instead of StringIO. Also, I added image mode to 'RGBA' since I have problems when displaying grey-scale images. Also, minor fixes.

Code:

import tkinter
from PIL import Image, ImageTk
from io import BytesIO
import requests

window = tkinter.Tk()

url = "https://s.yimg.com/os/weather/1.0.1/shadow_icon/60x60/partly_cloudy_night@2x.png"
r = requests.get(url)

pilImage = Image.open(BytesIO(r.content))
pilImage.mode = 'RGBA'
pilImage = pilImage.resize((50, 50), Image.ANTIALIAS)


image = ImageTk.PhotoImage(pilImage)

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

window.mainloop()
Phil
  • 67
  • 1
  • 8