Home > Enterprise >  How to resize image using Pillow and tkinter
How to resize image using Pillow and tkinter

Time:10-03

I am trying to display photos from NASA API but I only get the piece of this photo. I tried to change the geometry of the window app but I still have the same problem. Also, I tried to resize the image but I am getting errors.

import requests
from pprint import PrettyPrinter
import json
import datetime
from tkinter import *
from PIL import Image, ImageTk
from urllib.request import urlopen


root = Tk()
root.geometry("800x500")
root.title("Nasa photo of a day")


pp = PrettyPrinter()
api_key = 'PRIVATE KEY'
today_date = datetime.date.today()


URL_APOD = "https://api.nasa.gov/planetary/apod"
date = today_date
params = {
    'api_key': api_key,
    'date': date,
    'hd': 'True'
}
response_image = requests.get(URL_APOD, params=params)


json_data = json.loads(response_image.text)
image_url = json_data['hdurl']
print(image_url)


imageUrl = image_url
u = urlopen(imageUrl)
raw_data = u.read()
u.close()

nasa_img = ImageTk.PhotoImage(data=raw_data)
my_label1 = Label(image=nasa_img)
my_label1.pack()

root.mainloop()

This is how it looks like

And this is how is should looks like

CodePudding user response:

You can pass the result of urlopen(...) to PIL.Image() to fetch the image and then resize the image as below:

with urlopen(imageUrl) as fd:
    # fetch the image from URL and resize it to desired size
    image = Image.open(fd).resize((500,500))

nasa_img = ImageTk.PhotoImage(image)
my_label1 = Label(image=nasa_img)
my_label1.pack()
  • Related