Create an Image Downloader using Python

The Image Downloader is an application using which users can download images from their address and then display them. While downloading images normally can be a long task, this application simplifies the process by providing an interactive graphical user interface application.

The GUI of the project is created using the tkinter library of Python. It also uses the requests library for handling HTTP requests and the Pillow library for displaying downloaded images. This project provides a fun and practical approach to learning Python programming, GUI development, and fundamental image processing ideas.

Objectives of Python Image Downloader

The main objectives of this project are:

  • To develop a simple image downloader using python
  • To understand and apply basic concepts of GUI development with tkinter
  • To practice handling HTTP requests and image processing in Python using the pillow library and requests library.

Requirements for Python Image Downloader Project

  • Python 3
  • Tkinter library
  • Pillow Library
  • Requests Library
  • os library
Python Image Downloader Project

About Python Image Downloader Project

The image downloader project allows users to download images from their image address and then save them to a specified folder. This project displays the downloaded image within the GUI. If the folder is not specified, the image will be then saved in the ‘Downloads’ folder.

File Structure of Python Image Downloader

This project includes the following steps:

  1. Importing Libraries
  2. Downloading Image
  3. Displaying Image
  4. Handling the Download button, click
  5. Selecting Folder
  6. Creating the GUI

Step by Step Code Explanation of Python Image Downloader

Importing Libraries

import os
from requests import get, exceptions
from tkinter import *
from tkinter import messagebox, filedialog
from PIL import ImageTk , Image
  • The libraries this project uses are os, requests, tkinter and Pillow library
  • In the requests library, get is used for sending HTTP GET requests and exceptions are used for handling errors.
  • tkinter library is used for creating GUI. In tkinter, messagebox is used to display custom messages on the GUI window and filedialog is used for selecting the directory where an image should be saved.
  • In the PIL library, Image is used for saving images, and ImageTk is used for displaying images in the GUI window.

Downloading Image

def downloading_image(imageurl, folder):  
try:
response = get(imageurl, stream=True)
response.raise_for_status()
file_ext = response.headers.get('Content-Type', '').split('/')[-1].lower()
imagename = os.path.basename(imageurl).split('.')[0]
imagepath = os.path.join(folder, f"{imagename}.{file_ext}")
with open(imagepath, 'wb') as file:
for chunk in response.iter_content(1024):
file.write(chunk)
return imagepath
except exceptions.RequestException as req_error:
messagebox.showerror("Error", f"Download error: {req_error}")
except Exception as gen_error:
messagebox.showerror("Error", f"Unexpected error: {gen_error}")
  • The function def downloading_image() is created to download an image and it takes the imageurl and folder as arguments.
  • response = get(imageurl, stream=True) sends a get request to imageurl to download the image in small chunks.
  • response.raise_for_status() checks if the http request was successful.
  • file_ext, imagename and imagepath are variables for file extension of image, name of the image and its path, respectively.
  • Then, image data is written into a file at the specified path. If it is successful, imagepath is returned, otherwise an error is shown in the GUI messagebox.

Displaying Image

def show_image(imagepath):
try:
img = Image.open(imagepath)
img.thumbnail((1000, 1000))
img_tk = ImageTk.PhotoImage(img)
panel.config(image=img_tk)
panel.image = img_tk
messagebox.showinfo("Success", f"Image downloaded and displayed: {imagepath}")
except Exception as disp_error:
messagebox.showerror("Error", f"Error displaying image: {disp_error}")
  • The function show_image() is used for opening and displaying images within the tkinter application. It takes the argument of imagepath.
  • At first, the image is opened using the Image.open() of the Pillow library. Then, it is resized into 1000 x 1000 pixels by the thumbnail method.
  • Using the PhotoImage class of the ImageTk module, we convert it into a format suitable for displaying in tkinter.
  • After displaying the image successfully, an messagebox shows saying that image is downloaded and displayed, otherwise the messagebox shows the error.

Handling the Download button click.

def on_download_click():
imageurl = imageaddress_entry.get()
folder = path_entry.get()
if not imageurl:
messagebox.showerror("Error", "Image Address is required.")
return
if not folder:
messagebox.showinfo("Info", "Folder not selected")
folder = os.path.join(os.getcwd(), 'Downloads')
os.makedirs(folder, exist_ok=True)
imagepath = downloading_image(imageurl, folder)
if imagepath:
show_image(imagepath)
  • This function is made as an event handler which triggers when we click the download button.
  • First, it checks the entries in the imageurl and folder fields. If imageurl is empty, it displays the message image address is required and if the folder is empty, then it displays the message folder not selected and automatically selects the downloads folder of the current working directory.
  • After checking both fields, it calls the downloading_image function.
  • After the imagepath is returned, the show_image() function displays the downloaded image.

Selecting Folder

def select_folder():
folder = filedialog.askdirectory()
if folder:
path_entry.delete(0, END)
path_entry.insert(0, folder)
  • This function is used to select the folder where the downloaded image should be saved.
  • We select the folder where the image should be saved using filedialog.askdirectory().
  • After selecting the folder, it deletes any text in the folder entry and then adds the content of the folder variable to it.

Creating GUI

def create_gui():
app = Tk()
app.title("Image Downloader Application")
app.config (bg="#013220")
Label(app, text="Image Address:").pack(pady=7)
global imageaddress_entry
imageaddress_entry = Entry(app, width=50)
imageaddress_entry.pack(pady=7)
Label(app, text="Save to folder:").pack(pady=7)
global path_entry
path_entry = Entry(app, width=50)
path_entry.pack(pady=7)
Button(app, text="Browse", command=select_folder).pack(pady=7)
Button(app, text="Download Image", command=on_download_click).pack(pady=20)
global panel
panel = Label(app)
panel.pack(pady=50)
app.mainloop()
create_gui()
  • The GUI of our project is created using the create_gui() function.
  • Tk object is used to create the main application window
  • Various elements like labels and buttons are added in the main application window like Image Address, Save to Folder and buttons like Browse and Download Image
  • The browse button triggers the select_folder function, and the Download Image button triggers the on_download_click function.
  • The mainloop() method is called to start the tkinter event loop. It makes the tkinter application responsive.
  • At the end, create_gui() function is called so that the application is created when the script runs.

Complete Code

import os
from requests import get, exceptions
from tkinter import *
from tkinter import messagebox, filedialog
from PIL import ImageTk , Image
def downloading_image(imageurl, folder):
try:
response = get(imageurl, stream=True)
response.raise_for_status()
file_ext = response.headers.get('Content-Type', '').split('/')[-1].lower()
imagename = os.path.basename(imageurl).split('.')[0]
imagepath = os.path.join(folder, f"{imagename}.{file_ext}")
with open(imagepath, 'wb') as file:
for chunk in response.iter_content(1024):
file.write(chunk)
return imagepath
except exceptions.RequestException as req_error:
messagebox.showerror("Error", f"Download error: {req_error}")
except Exception as gen_error:
messagebox.showerror("Error", f"Unexpected error: {gen_error}")
def show_image(imagepath):
try:
img = Image.open(imagepath)
img.thumbnail((1000, 1000))
img_tk = ImageTk.PhotoImage(img)
panel.config(image=img_tk)
panel.image = img_tk
messagebox.showinfo("Success", f"Image downloaded and displayed: {imagepath}")
except Exception as disp_error:
messagebox.showerror("Error", f"Error displaying image: {disp_error}")
def on_download_click():
imageurl = imageaddress_entry.get()
folder = path_entry.get()
if not imageurl:
messagebox.showerror("Error", "Image Address is required.")
return
if not folder:
messagebox.showinfo("Info", "Folder not selected")
folder = os.path.join(os.getcwd(), 'Downloads')
os.makedirs(folder, exist_ok=True)
imagepath = downloading_image(imageurl, folder)
if imagepath:
show_image(imagepath)
def select_folder():
folder = filedialog.askdirectory()
if folder:
path_entry.delete(0, END)
path_entry.insert(0, folder)
def create_gui():
app = Tk()
app.title("Image Downloader Application")
app.config (bg="#013220")
Label(app, text="Image Address:").pack(pady=7)
global imageaddress_entry
imageaddress_entry = Entry(app, width=50)
imageaddress_entry.pack(pady=7)
Label(app, text="Save to folder:").pack(pady=7)
global path_entry
path_entry = Entry(app, width=50)
path_entry.pack(pady=7)
Button(app, text="Browse", command=select_folder).pack(pady=7)
Button(app, text="Download Image", command=on_download_click).pack(pady=20)
global panel
panel = Label(app)
panel.pack(pady=50)
app.mainloop()
create_gui()

Python Image Downloader Output

Python Image Downloader Output
Python Image Downloader Project Output
Image Downloader using Python Output
Python Image Downloader Final Output

Conclusion

With this project in Python, we have successfully created an Image Downloader application in Python using the requests library for handling HTTP requests, the Pillow library for image processing and the tkinter library for creating the GUI. By understanding and modifying this project, you can learn important Python programming and GUI development concepts.

Learn more Create an Image Downloader using Python

Leave a Reply