Coding hints

How to create a simple Image converter using Javascript, PHP or Python

There are many online tools nowadays one can use to convert images for free. Here, we will be showing you how you can create a simple image converter using Javascript, PHP or Python.

Many image formats are native to one specific graphics application and are not offered as an export option in other software, due to proprietary considerations. An example of this is Adobe Photoshop’s native PSD format (Prevention of Significant Deterioration), which cannot be opened in less sophisticated programs for image viewing or editing, such as Microsoft Paint. Most image editing software is capable of importing and exporting in a variety of formats though, and a number of dedicated image converters exist.

Creating a simple image converter using PHP

Here’s an example PHP script for converting images from one format to another using the GD library:

<?php

// Set input and output directories
$input_dir = 'input_images';
$output_dir = 'output_images';

// Ensure output directory exists
if (!file_exists($output_dir)) {
    mkdir($output_dir);
}

// Loop through all files in input directory
foreach (scandir($input_dir) as $file_name) {

    // Ignore any files that are not images
    if (!preg_match('/\.(jpg|jpeg|png)$/', $file_name)) {
        continue;
    }

    // Load image file
    $image_path = $input_dir . '/' . $file_name;
    $image = imagecreatefromstring(file_get_contents($image_path));

    // Set output file path and format
    $output_path = $output_dir . '/' . pathinfo($file_name, PATHINFO_FILENAME) . '.png';

    // Convert image format and save to output directory
    imagepng($image, $output_path);

    echo "Converted $file_name to $output_path\n";
}

In this example, we first set the input and output directories for our images, and create the output directory if it doesn’t already exist.

We then loop through all files in the input directory, checking each one to see if it is an image (using a regular expression). For each image, we load it into a GD image resource using imagecreatefromstring(), and specify the output file path and format (in this case, converting to PNG).

We then use the imagepng() function to convert the image to PNG format and save it to the output directory.

As the script runs, it will print a message for each image converted, indicating the original file name and the new output file path.

Sample with HTML and Javascript

Here’s an example of how you can use HTML and JavaScript to convert an image file from one format to another in the browser:

<!DOCTYPE html>
<html>
<head>
  <title>Image Converter</title>
</head>
<body>
  <input type="file" id="input-file">
  <button onclick="convert()">Convert</button>
  <br><br>
  <canvas id="output-canvas"></canvas>
  <a id="download-link" href="#" download></a>

  <script>
    function convert() {
      // Get input file and create an image object
      const input = document.getElementById('input-file').files[0];
      const img = new Image();
      img.src = URL.createObjectURL(input);

      // When image has loaded, create canvas and draw image on it
      img.onload = function() {
        const canvas = document.getElementById('output-canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        // Convert canvas to image file of desired format
        const output = canvas.toDataURL('image/png');
        const downloadLink = document.getElementById('download-link');
        downloadLink.href = output;
        downloadLink.download = 'output.png';
        downloadLink.click();
      };
    }
  </script>
</body>
</html>

In this example, we first create an HTML file with an input element for selecting an image file, a button for triggering the conversion, a canvas element for displaying the output image, and an anchor element with an empty href and a download attribute for downloading the converted image.

We then use JavaScript to add an event listener to the button that triggers the conversion. When the button is clicked, we get the input file and create an image object with its source set to a URL object created from the input file. We then wait for the image to load, and when it has, we create a canvas element with the same dimensions as the image, and draw the image onto the canvas using its 2D context.

Finally, we use the toDataURL() method of the canvas to convert it to an image file of the desired format (in this case, PNG), and set the href and download attributes of the download link to the output data URL and desired file name. We then programmatically click the download link to initiate the download of the converted image.

Example Python code for creating a simple image converter

Here’s an example Python script for converting images from one format to another using the Pillow library:

from PIL import Image
import os

# Set input and output directories
input_dir = 'input_images'
output_dir = 'output_images'

# Ensure output directory exists
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# Loop through all files in input directory
for file_name in os.listdir(input_dir):

    # Ignore any files that are not images
    if not file_name.endswith('.jpg') and not file_name.endswith('.jpeg') and not file_name.endswith('.png'):
        continue

    # Load image file
    image_path = os.path.join(input_dir, file_name)
    with Image.open(image_path) as image:

        # Set output file path and format
        output_path = os.path.join(output_dir, file_name.split('.')[0] + '.png')

        # Convert image format and save to output directory
        image.save(output_path, 'PNG')

        print(f"Converted {file_name} to {output_path}")

In this example, we first import the necessary modules, including the Pillow library for image manipulation. We then specify the input and output directories for our images and create the output directory if it doesn’t already exist.

We then loop through all files in the input directory, checking each one to see if it is an image (using file extensions). For each image, we load it into a PIL Image object, specify the output file path and format (in this case, converting to PNG), and save the converted image to the output directory.

As the script runs, it will print a message for each image converted, indicating the original file name and the new output file path.

Back to top button

Adblock Detected!

Hello, we detected you are using an Adblocker to access this website. We do display some Ads to make the revenue required to keep this site running. please disable your Adblock to continue.