Building an Image Converter WebApp with Python and Streamlit: A Comprehensive Guide

Building an Image Converter WebApp using Python and Streamlit is an excellent way to create an interactive application that allows users to upload images, convert them into different formats, and download the converted files—all from a web browser. This guide will walk you through the process step-by-step.

Building an Image Converter WebApp with Python and Streamlit: A Comprehensive Guide
Building an Image Converter WebApp with Python and Streamlit: A Comprehensive Guide

Streamlit is an open-source Python library that makes it easy to create and share custom web apps for machine learning and data science. Using Streamlit along with the Pillow library (a fork of the Python Imaging Library), we can build an app that converts images between formats like PNG, JPEG, BMP, GIF, and TIFF.

Prerequisites

  • Python 3.7 or later installed on your system.
  • Basic knowledge of Python programming.
  • Familiarity with command-line operations.

Setting Up the Environment

First, ensure you have Python and pip installed. Then, follow these steps:

  1. Create a Virtual Environment (optional but recommended): python -m venv venv
  2. Activate the Virtual Environment:
    • On Windows: venv\Scripts\activate
    • On macOS/Linux: source venv/bin/activate
  3. Install Required Libraries: pip install streamlit Pillow

Building the WebApp

Create a new Python file named app.py in your project directory. We’ll build the app step by step.

1. Import Libraries

import streamlit as st
from PIL import Image
import io
  • streamlit: For building the web interface.
  • PIL (Pillow): For image processing.
  • io: For handling byte streams.

2. Set Up the App Interface

st.title("Image Converter WebApp")
st.write("Upload an image and convert it to a different format.")
  • st.title: Sets the title of the app.
  • st.write: Adds descriptive text.

3. Upload and Display Image

uploaded_file = st.file_uploader(
    "Choose an image...", type=["png", "jpg", "jpeg", "bmp", "gif", "tiff"]
)

if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image", use_column_width=True)
  • st.file_uploader: Allows users to upload images of specified types.
  • st.image: Displays the uploaded image.

4. Select Output Format

    format_options = ["PNG", "JPEG", "BMP", "GIF", "TIFF"]
    output_format = st.selectbox("Select output format:", format_options)
  • st.selectbox: Provides a dropdown menu for format selection.

5. Image Conversion

    if st.button("Convert"):
        converted_img_io = io.BytesIO()
        image.save(converted_img_io, format=output_format)
        converted_img_io.seek(0)
  • st.button: Adds a button to trigger conversion.
  • io.BytesIO(): Creates an in-memory byte-stream object.
  • image.save: Saves the image in the selected format to the byte-stream.
  • seek(0): Resets the stream’s position to the beginning.

6. Download Converted Image

        st.download_button(
            label="Download Converted Image",
            data=converted_img_io,
            file_name=f"converted_image.{output_format.lower()}",
            mime=f"image/{output_format.lower()}",
        )
  • st.download_button: Allows users to download the converted image.

Running the App

Save the app.py file and run the following command in your terminal:

streamlit run app.py

This command starts a local server and opens the app in your default web browser.

Enhancements

To make the app more versatile, you can add features like image resizing, cropping, or applying filters.

Adding Image Resizing Option

    resize = st.checkbox("Resize Image?")
    if resize:
        new_width = st.number_input("New Width", min_value=1, value=image.width)
        new_height = st.number_input("New Height", min_value=1, value=image.height)
        image = image.resize((new_width, new_height))
        st.image(image, caption="Resized Image", use_column_width=True)
  • st.checkbox: Adds a checkbox to toggle resizing.
  • st.number_input: Inputs for new width and height.
  • image.resize: Resizes the image to the new dimensions.

Deploying the App

You can deploy your Streamlit app to share it with others:

  • Streamlit Community Cloud: https://streamlit.io/cloud
  • Heroku: Deploy using a Procfile and requirements.txt.
  • Docker: Containerize your app and deploy to any cloud service.

Complete Code

Here’s the full code for the Image Converter WebApp:

import streamlit as st
from PIL import Image
import io

st.title(" Image Converter WebApp")
st.write("Upload an image and convert it to a different format.")

uploaded_file = st.file_uploader(
    "Choose an image...", type=["png", "jpg", "jpeg", "bmp", "gif", "tiff"]
)

if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image", use_column_width=True)

    format_options = ["PNG", "JPEG", "BMP", "GIF", "TIFF"]
    output_format = st.selectbox("Select output format:", format_options)

    resize = st.checkbox("Resize Image?")
    if resize:
        new_width = st.number_input("New Width", min_value=1, value=image.width)
        new_height = st.number_input("New Height", min_value=1, value=image.height)
        image = image.resize((int(new_width), int(new_height)))
        st.image(image, caption="Resized Image", use_column_width=True)

    if st.button("Convert"):
        converted_img_io = io.BytesIO()
        image.save(converted_img_io, format=output_format)
        converted_img_io.seek(0)

        st.download_button(
            label="Download Converted Image",
            data=converted_img_io,
            file_name=f"converted_image.{output_format.lower()}",
            mime=f"image/{output_format.lower()}",
        )

Note: Ensure you handle exceptions and errors appropriately in a production environment to make the app robust.

Conclusion

By following our code, you will successfully build an Image Converter WebApp using Python and Streamlit. This app allows users to upload images, convert them to different formats, and download the converted files—all through a simple web interface.

Additional Resources

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

    Comments