Open In App

Shell Script Program to Convert Image Formats

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Image Format Conversion is one of the most common processes in different fields like Web Development, Graphic Design, etc. As in Linux Environment, we have a Shell Scripting tool that can be used to automate the process of converting the image formats in a couple of seconds. We can convert the images from one format (e.g. PNG) to another (e.g. JPEG) or vice versa using Shell Script. We can develop a menu-driven approach, which will enable users to select the conversion type, input and output filenames, etc.

Prerequisites:

  1. Linux Environment: This tutorial assumes you are working in a Linux environment. The provided instructions and script are tailored for Linux systems.
  2. Terminal Access: You should have access to a terminal or command-line interface on your Linux system. Most Linux distributions provide this by default.

Example:

Image Format Converter
----------------------
1. Convert PNG to JPEG
2. Convert JPEG to PNG
3. Exit
Enter your choice: 1

Input:
Enter the input PNG file: input.png
Enter the output JPEG file: output.jpg

Output:
Conversion complete!
Press Enter to continue...

Here our main task is to write the script which will be used to convert the image format (PNG to JPEG) and vice-versa. Here, we user can be able to select the format conversion type, enter the input image, and also specify the output image. The script will convert the input image and save it in the desired format on the system.

Creating the Script

Step 1: The script defines a function called display_menu, which is responsible for clearing the terminal screen and presenting a menu of options to the user. It uses the echo command to display the menu, offering two image format conversion options (PNG to JPEG and JPEG to PNG) and an option to exit.

#!/bin/bash
display_menu() {
    clear           
    echo "Image Format Converter"  
    echo "----------------------"
    echo "1. Convert PNG to JPEG" 
    echo "2. Convert JPEG to PNG"  
    echo "3. Exit"  
}

Step 2: The second step has two functions for input validation. The validate_file_existence function checks if a given file exists. If the file does not exist, it displays an error message. The validate_file_extension function verifies that a file has the correct extension. If the extension is incorrect, it also displays an error message. These functions help ensure that the user provides valid input files.

validate_file_existence() {
    local file="$1"
    if [ ! -e "$file" ]; then    
        echo "Error: File '$file' does not exist."
        return 1
    fi
}
validate_file_extension() {
    local file="$1"
    local allowed_extension="$2"
    local file_extension="${file##*.}"  

    if [ "$file_extension" != "$allowed_extension" ]; then
        echo "Error: Invalid file extension. Expected '$allowed_extension' file."
        return 1
    fi
}

Step 3: In this step, the script checks whether ImageMagick is installed on the system using the command -v convert command. If ImageMagick is not found, the install_imagemagick function is called, prompting the user to install it. The user can choose to install ImageMagick using system package management tools. If the user declines to install it, the script exits with a message indicating that ImageMagick is necessary for the script’s functionality.

install_imagemagick() {
    echo "ImageMagick is not installed. Do you want to install it? (y/n)"
    read choice
    if [ "$choice" == "y" ]; then
        sudo apt-get update
        sudo apt-get install imagemagick
    else
        echo "ImageMagick is required for this script to work. Please install it manually."
        exit 1
    fi
}

# Check if ImageMagick is installed
if ! command -v convert &> /dev/null; then
    install_imagemagick
fi

list_available_images() {
    cd /home/kali/Desktop  
    echo "Available image files in the current directory:"
    for file in *.{png,jpeg,jpg}; do
        [ -e "$file" ] || continue
        echo "$file"
    done
}


Step 4: In this step, two functions for image format conversion are defined: convert_png_to_jpeg and convert_jpeg_to_png. These functions prompt the user to enter input and output filenames. Before performing the conversion, they validate the input file’s existence and extension using the functions from Step 2. If the validation is successful, the conversion is executed using the convert command from ImageMagick, and a success message is displayed.

convert_png_to_jpeg() {
    list_available_images
    read -p "Enter the input PNG file: " input_file
    read -p "Enter the output JPEG file: " output_file
    if validate_file_existence "$input_file" && validate_file_extension "$input_file" "png"; then
        convert "$input_file" "$output_file"
        echo "Conversion complete!"
        read -p "Press Enter to continue..."
    else
        read -p "Press Enter to continue..."
    fi
}
convert_jpeg_to_png() {
    list_available_images
    read -p "Enter the input JPEG file: " input_file
    read -p "Enter the output PNG file: " output_file

    if validate_file_existence "$input_file" && validate_file_extension "$input_file" "jpeg"; then
        convert "$input_file" "$output_file"
        echo "Conversion complete!"
        read -p "Press Enter to continue..."
    else
        read -p "Press Enter to continue..."
    fi
}


Step 5: The final step of the script includes a while loop that runs indefinitely, allowing the user to interact with the menu. It continuously displays the menu and prompts the user to choose an option. Based on the user’s choice, it calls the respective conversion function. If the user chooses to exit, the script displays a goodbye message and terminates. If the user selects an invalid option, an error message is shown, prompting the user to try again.

while true; do
    display_menu              
    read -p "Enter your choice: " choice
    case $choice in
        1) convert_png_to_jpeg ;;  
        2) convert_jpeg_to_png ;;  
        3) echo "Exiting. Goodbye!"; exit 0 ;;  
        *) echo "Invalid choice. Please try again." 
    esac
done


Steps to create and execute a bash script

Step 1: Open the terminal window using the keyboard shortcut “Ctrl + Alt + T“.

Opening Terminal

Opening Terminal

Step 2: Using any text editor like Vim, vi, or Nano, open a new blank file in the text editor.

nano imgformats.sh
Creating script in nano editor

Creating script in nano editor

Step 3: Now, we need to write the below script in the created file imgformats.sh.

#!/bin/bash
display_menu() {
    clear
    echo "Image Format Converter"
    echo "----------------------"
    echo "1. Convert PNG to JPEG"
    echo "2. Convert JPEG to PNG"
    echo "3. Exit"
}
validate_file_existence() {
    local file="$1"
    if [ ! -e "$file" ]; then
        echo "Error: File '$file' does not exist."
        return 1
    fi
}
validate_file_extension() {
    local file="$1"
    local allowed_extension="$2"
    local file_extension="${file##*.}"
    
    if [ "$file_extension" != "$allowed_extension" ]; then
        echo "Error: Invalid file extension. Expected '$allowed_extension' file."
        return 1
    fi
}
install_imagemagick() {
    echo "ImageMagick is not installed. Do you want to install it? (y/n)"
    read choice
    if [ "$choice" == "y" ]; then
        sudo apt-get update
        sudo apt-get install imagemagick
    else
        echo "ImageMagick is required for this script to work. Please install it manually."
        exit 1
    fi
}
if ! command -v convert &> /dev/null; then
    install_imagemagick
fi
list_available_images() {
    cd /home/kali/Desktop  # Change to the specified directory
    echo "Available image files in the current directory:"
    for file in *.{png,jpeg,jpg}; do
        [ -e "$file" ] || continue
        echo "$file"
    done
}
convert_png_to_jpeg() {
    list_available_images
    read -p "Enter the input PNG file: " input_file
    read -p "Enter the output JPEG file: " output_file
    if validate_file_existence "$input_file" && validate_file_extension "$input_file" "png"; then
        convert "$input_file" "$output_file"
        echo "Conversion complete!"
        read -p "Press Enter to continue..."
    else
        read -p "Press Enter to continue..."
    fi
}
convert_jpeg_to_png() {
    list_available_images
    read -p "Enter the input JPEG file: " input_file
    read -p "Enter the output PNG file: " output_file
    if validate_file_existence "$input_file" && validate_file_extension "$input_file" "jpeg"; then
        convert "$input_file" "$output_file"
        echo "Conversion complete!"
        read -p "Press Enter to continue..."
    else
        read -p "Press Enter to continue..."
    fi
}
while true; do
    display_menu
    read -p "Enter your choice: " choice

    case $choice in
        1) convert_png_to_jpeg ;;
        2) convert_jpeg_to_png ;;
        3) echo "Exiting. Goodbye!"; exit 0 ;;
        *) echo "Invalid choice. Please try again."
    esac
done
Script Written in File

Script Written in File

Step 4: Now, as we have created the script, we need to make the script executable by running the chmod command in the terminal.

chmod +x imgformats.sh
Granting Executable Permissions

Granting Executable Permissions

Step 5: Finally, we need to execute the script by using the below command.

./imgformats.sh

Output 1:

Output 1

Output 1

Explanation:

In the above output, we can see that we have executed the script and chosen the Choce to convert the PNG to JPEG file. After selecting the choice, the script have mentioned the aviable image files in the current directory. We have (gfgimg.png) file which we will be converting to JPEG format. We have given the file name as input (gfgimg.png) and output JPEG filename is specieif as (output.jpeg). The script have done the conversion from PNG to JPEG.

Output 2:

Output 2

Output 2

Explanation:

In the above screenshot, we can see that once the conversion is been done. We have listed all the files present in the directory. There is input file and the converted file (output.jpeg) present in the directory. This assures that our conversion is done successfully.

Frequently Asked Questions

Q1. What is ImageMagick, and why does the script use it for image format conversion?

Answer:

ImageMagick is a widely used open-source software suite for image manipulation. The script uses it for image format conversion because it provides a powerful command-line tool called convert that can perform various image operations, including format conversion, making it a convenient choice for automating such tasks.

Q2. How do I specify the input and output image filenames in the script?

Answer:

The script prompts you to enter the input and output filenames when you choose an image format conversion option. Simply type the filenames in the terminal, and the script will perform the conversion accordingly.

Q3. Can I customize the list of supported image formats in the script?

Answer:

Yes, you can customize the list of supported image formats by modifying the pattern in the list_available_images function. You can add or remove file extensions (e.g., .jpg, .bmp) in the {} block as needed.

Q4. What should I do if the script reports that ImageMagick is not installed?

Answer:

If you see the message “ImageMagick is not installed,” the script will prompt you to install it. Follow the on-screen instructions. If you choose not to install it, the script will exit. You can manually install ImageMagick on your system to use the script’s image conversion functionality.

Q5. Can this script handle batch conversion of multiple images at once?

Answer:

The script is designed for single-image conversions, but you can create a loop or use other shell scripting techniques to perform batch conversions by extending the script’s functionality.

Conclusion

In conclusion, this shell script provides a straightforward and user-friendly way to convert image formats. It simplifies the process of changing an image’s format by presenting a clear menu, validating input, and giving feedback upon conversion. Shell scripts like this can save time and reduce the chance of mistakes, making them valuable tools for streamlining routine tasks.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads