Convert PNG to JPG Using Python and Tkinter | Download Source Code

Faraz

By Faraz - July 10, 2023

Learn how to convert PNG images to JPG format effortlessly using Python and Tkinter. Download the source code and follow the step-by-step tutorial.


Convert PNG to JPG Using Python and Tkinter  Download Source Code.jpg

Are you looking for a way to convert PNG images to JPG format using Python and Tkinter? You've come to the right place! In this article, we will walk you through the process of converting PNG files to JPG using the power of Python programming language and the user-friendly Tkinter library. By the end of this guide, you will have a clear understanding of how to accomplish this task and even download the source code to try it out yourself.

Table of Contents

  1. Introduction
  2. What is PNG?
  3. What is JPG?
  4. Why Convert PNG to JPG?
  5. Setting Up the Environment
  6. Installing Required Libraries
  7. Full Source Code
  8. Explanation of Source Code
  9. Packaging the Application
  10. Conclusion
  11. FAQs

1. Introduction

Images play a crucial role in various applications and projects. Sometimes, it becomes necessary to convert images from one format to another to meet specific requirements. In this tutorial, we will focus on converting PNG (Portable Network Graphics) images to JPG (Joint Photographic Experts Group) format. We will achieve this using Python, a powerful and versatile programming language, along with Tkinter, a popular Python GUI toolkit.

2. What is PNG?

PNG is a widely used image format that supports lossless data compression. It was designed as an improved alternative to GIF (Graphics Interchange Format) and supports a full range of color depths, transparency, and alpha channel. PNG images are commonly used in web design, digital art, and graphic design.

3. What is JPG?

JPG, also known as JPEG (Joint Photographic Experts Group), is a popular image format used for storing and transmitting photographs and realistic images. It utilizes lossy compression, which reduces file size by sacrificing some image quality. JPG images are widely supported by various devices and applications, making them a suitable choice for sharing images online.

4. Why Convert PNG to JPG?

While PNG is a versatile format, it tends to have larger file sizes compared to JPG. Converting PNG images to JPG can significantly reduce file sizes without significant loss in image quality. This is especially useful when dealing with large collections of images or when optimizing web page loading times. Converting PNG to JPG can help save storage space and improve overall performance.

5. Setting Up the Environment

Before we begin, let's make sure we have the necessary environment set up for our Python development. Here are the steps to follow:

  • Install Python: Visit the official Python website and download the latest version of Python for your operating system. Follow the installation instructions provided.
  • Install Tkinter: Tkinter is a standard Python library for creating graphical user interfaces. Most Python installations come with Tkinter pre-installed. However, if you don't have it, you can install it using the package manager that comes with your Python distribution.

6. Installing Required Libraries

To convert PNG to JPG, we will need the help of additional Python libraries. Let's install the required libraries using the pip package manager. Open your terminal or command prompt and run the following commands:

pip install Pillow

The Pillow library provides support for opening, manipulating, and saving various image file formats, including PNG and JPG.

7. Full Source Code

from tkinter import Tk, Button, Label, Frame
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk


def convert_to_jpg():
    global image_label, filename_label, saved_label

    if image_path:
        # Open the image using PIL
        image = Image.open(image_path)

        # Convert the image to RGB if it has an RGBA color mode
        if image.mode == 'RGBA':
            image = image.convert('RGB')

        # Convert the image to JPG format
        jpg_filename = image_path.replace('.png', '.jpg')
        image.save(jpg_filename, 'JPEG')

        saved_label.config(text=f"Saved as: {jpg_filename}")
        print(f"Image converted and saved as {jpg_filename}.")


def open_image():
    global image_path, image_label, filename_label

    # Open a file dialog to select an image file
    Tk().withdraw()
    image_path = askopenfilename(filetypes=[("Png Files", ".png")])

    if image_path:
        # Open the image using PIL
        image = Image.open(image_path)

        # Resize the image to a square preview
        size = min(image.size)
        image = image.crop((0, 0, size, size))
        image = image.resize((400, 400))

        # Create a PhotoImage from the PIL image
        photo = ImageTk.PhotoImage(image)

        # Update the image label with the new image
        image_label.configure(image=photo)
        image_label.image = photo

        # Update the filename label
        filename_label.config(text=f"Selected file: {image_path}")

# Create a Tkinter window
window = Tk()
window.title("PNG to JPG Converter")
window.geometry("600x600")
window.resizable(False, False)

# Create a frame for the image label
image_frame = Frame(window, width=250, height=200, relief="solid")
image_frame.place(x=50, y=20)

# Create an image label for preview
image_label = Label(image_frame)
image_label.pack(padx=50, pady=20)

# Create a label for the selected filename
filename_label = Label(window, text="Selected file: None", font=("Arial", 12))
filename_label.place(x=0, y=470)

# Create a button to open the image
open_button = Button(window, text="Open Image", command=open_image, font=("Arial", 14))
open_button.place(x=0, y=500)

# Create a button to convert the image
convert_button = Button(window, text="Convert to JPG", command=convert_to_jpg, font=("Arial", 14))
convert_button.place(x=150, y=500)

# Create a label for the saved file
saved_label = Label(window, font=("Arial", 12))
saved_label.place(x=0, y=550)

previewtext_label = Label(window, text="Preview", font=("Arial", 18))
previewtext_label.place(x=250, y=10)

# Initialize the image path variable
image_path = None

# Start the Tkinter event loop
window.mainloop()

8. Explanation of Source Code

Let's go through the code step by step:

The necessary modules are imported:

  • Tk from tkinter: Used to create the main window and other GUI elements.
  • Button, Label, and Frame from tkinter: Used to create buttons, labels, and frames in the GUI.
  • askopenfilename from tkinter.filedialog: Used to open a file dialog and select an image file.
  • Image and ImageTk from PIL (Python Imaging Library): Used for image manipulation and displaying images in the GUI.

Two global variables, image_path and image_label, are declared. They are used to keep track of the selected image file path and the label displaying the image preview.

The convert_to_jpg() function is defined. This function is called when the "Convert to JPG" button is clicked. It performs the following steps:

  • Checks if an image file is selected (image_path is not empty).
  • Opens the image using PIL.
  • Converts the image to RGB mode if it has an RGBA color mode (transparency).
  • Creates a new file name for the converted image by replacing the file extension from ".png" to ".jpg".
  • Saves the converted image as a JPG file.
  • Updates the saved_label label to display the path of the saved JPG file.
  • Prints a message indicating that the image has been converted and saved.

The open_image() function is defined. This function is called when the "Open Image" button is clicked. It performs the following steps:

  • Opens a file dialog to select an image file with the extension ".png".
  • If an image file is selected:
  • Opens the image using PIL.
  • Resizes the image to a square preview by cropping and resizing it.
  • Creates a PhotoImage object from the PIL image.
  • Updates the image_label with the new image, displaying the preview.
  • Updates the filename_label to show the selected file path.

The Tkinter window is created, with the title "Image to JPG Converter" and dimensions 600x600. It is set to be non-resizable.

A frame (image_frame) is created to hold the image preview. It is positioned at coordinates (50, 20) on the window.

An image label (image_label) is created within the frame to display the image preview. It is initially empty.

A label (filename_label) is created to display the selected file path. It is initially set to "Selected file: None" and positioned at coordinates (0, 470) on the window.

A button (open_button) is created with the label "Open Image". It is assigned the open_image() function as the command to be executed when clicked. It is positioned at coordinates (0, 500) on the window.

A button (convert_button) is created with the label "Convert to JPG". It is assigned the convert_to_jpg() function as the command to be executed when clicked. It is positioned at coordinates (150, 500) on the window.

A label (saved_label) is created to display the path of the saved JPG file. It is initially empty and positioned at coordinates (0, 550) on the window.

A label (previewtext_label) is created withthe label "Preview". It is positioned at coordinates (250, 10) on the window.

The image_path variable is initialized as None. This variable will store the path of the selected image file.

The Tkinter event loop (window.mainloop()) is started, which keeps the GUI window open and handles user interactions.

9. Packaging the Application

To share your application with others, you can package it into an executable file using tools like PyInstaller or cx_Freeze. This allows users to run the converter without requiring a Python installation. Packaging the application also provides a more user-friendly experience. Refer to the documentation of your chosen packaging tool for detailed instructions on how to proceed.

10. Conclusion

In this article, we have explored how to convert PNG images to JPG format using Python and Tkinter. We discussed the importance of converting images for various purposes and outlined the steps involved in the conversion process. By following the provided code snippets and instructions, you should now be able to create your own PNG to JPG converter application. Feel free to experiment with additional features and improvements to enhance the functionality and usability of your application.

11. FAQs

Q1. Can I convert multiple PNG files to JPG at once using this method?

Yes, you can modify the code to handle batch conversion by allowing the user to select multiple files and iterating over them.

Q2. Does the conversion process affect the quality of the image?

The conversion from PNG to JPG involves some loss in image quality due to the compression applied. However, by using the RGB color mode, the impact on image quality is minimal.

Q3. Can I convert JPG images to PNG using the same method?

While this article focuses on converting PNG to JPG, you can apply a similar approach to convert JPG images to PNG by changing the output format in the code.

Q4. Is Tkinter the only option for creating a GUI in Python?

No, Tkinter is one of the many options available for creating GUI applications in Python. Other popular choices include PyQt, PySide, and wxPython.

Q5. Where can I download the source code for this PNG to JPG converter?

You can copy the complete source code for this PNG to JPG converter from the above section.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺