Image format Converter Using HTML, CSS, and JavaScript | Step-by-Step Guide

Learn how to create an image format converter website with HTML, CSS, and JavaScript, complete with code examples and explanations


Introduction:

An image format converter is a tool that can transform images from one file format to another. It's useful for a variety of reasons, such as when you need to convert a file to a different format in order to make it compatible with a specific program or device, or when you want to compress an image to a smaller size without losing too much quality.

In this tutorial, we will be creating our own image format converter website using HTML, CSS, and JavaScript. We will guide you step by step through the process of building a functional image converter that allows users to upload an image, select the desired output format, and download the converted file. By the end of this tutorial, you will have a working image converter website that you can use to convert images in a few simple clicks. So, let's get started!


Section 1: Setting Up the HTML

In this section, we'll start by setting up the basic HTML structure for our image format converter. The HTML structure will include a container div, header, input file element, preview and options containers with their respective elements.

Firstly, let's discuss the basic structure of an HTML document. An HTML document has two main parts, the head and the body. The head includes the document's title, meta tags, links to external stylesheets and scripts. The body contains the visible content of the webpage.

Let's create our container div, header, and input file element:

<!DOCTYPE html>

<html>

<head>

    <title>Image Format Converter</title>

</head>

<body>

    <div id="container">

        <h1>Image Format Converter</h1>

        <input type="file" id="input-file">

    </div>

</body>

</html>


Next, we'll add the preview and options containers with their respective elements:

<!DOCTYPE html>

<html>

<head>

    <title>Image Format Converter</title>

</head>

<body>

    <div id="container">

        <h1>Image Format Converter</h1>

        <input type="file" id="input-file">

        <br><br>

        <div id="options-container">

            <label for="format-select">Select format:</label>

            <select id="format-select">

                <option value="jpeg">JPEG</option>

                <option value="png">PNG</option>

                <option value="tiff">TIFF</option>

                <option value="gif">GIF</option>

            </select>

            <br><br>

            <button id="convert-button">Convert and Download</button>

        </div>

        <br><br>

        <div id="preview-container">

            <img id="preview-image" src="#" alt="Image Preview">

        </div>

    </div>

</body>

</html>


The container div is the main wrapper for our content. The header contains the title of our app, and the input file element is where the user selects the image file they want to convert. The options container includes a label and select element, which allow the user to select the desired format for the output image. The convert button is where the user will initiate the image conversion process. Lastly, the preview container will display a preview of the selected image.

Let's add some basic styling to our HTML elements:

<head>

<title>Image Format Converter</title>

<link rel="stylesheet" type="text/css" href="style.css">

</head>


CSS Styles:

#container {

  displayflex;

  flex-directioncolumn;

  align-itemscenter;

  border1px solid gray;

  padding3%;

  border-radius10px;

  width70%;

  margin10% auto;

  background-imageurl('https://wallpaperaccess.com/full/203514.jpg');

  background-repeatno-repeat;

  background-sizecover;

  colorazure;

}

input[type="file"] {

  padding10px;

  font-size16px;

  border2px solid #ddd;

  border-radius4px;

  margin-bottom20px;

  background-colorghostwhite;

}

#preview-container {

  width60%;

  displaynone;

}

#preview-image {

  width100%;

  heightauto;

}

#options-container {

  width60%;

  displayflex;

  flex-directioncolumn;

  align-itemscenter;

}


Section 2: Styling with CSS

Now that we have our basic HTML structure, it's time to add some style to our image format converter. We will be using CSS to add colors, fonts, background image and arrange the elements on the page.

Linking the Stylesheet to HTML Document

To link the CSS file to our HTML document, we need to add a link element inside the head section of the HTML document with a reference to our CSS file.

<head>

<title>Image Format Converter</title>

<link rel="stylesheet" type="text/css" href="style.css">

</head>


Styling the Page

We will use CSS to style the page. Here's the complete CSS code to style the page:

body {

  font-familyArialsans-serif;

  text-aligncenter;

}

h1 {

  font-family'Lobster'cursive;

  font-size36px;

  margin-bottom50px;

  colordarkcyan;

  margin-topauto;

  text-decorationunderline;

  letter-spacing2px;

}

#container {

  displayflex;

  flex-directioncolumn;

  align-itemscenter;

  border1px solid gray;

  padding3%;

  border-radius10px;

  width70%;

  margin10% auto;

  background-imageurl('https://wallpaperaccess.com/full/203514.jpg');

  background-repeatno-repeat;

  background-sizecover;

  colorazure;

}

input[type="file"] {

  padding10px;

  font-size16px;

  border2px solid #ddd;

  border-radius4px;

  margin-bottom20px;

  background-colorghostwhite;

}

#preview-container {

  width60%;

  displaynone;

}

#preview-image {

  width100%;

  heightauto;

}

#options-container {

  width60%;

  displayflex;

  flex-directioncolumn;

  align-itemscenter;

}

label {

  font-size18px;

  margin-bottom10px;

}

select {

  width100%;

  padding12px 20px;

  font-size16px;

  margin-bottom20px;

}

button {

  width100%;

  padding12px 20px;

  font-size16px;

  background-colorteal;

  colorwhite;

  cursorpointer;

}


Let's go through the CSS code to understand what each rule does:

  • body: sets the font-family and text alignment of the page.
  • h1: styles the page heading with a custom font-family, font size, color, and underlines it.
  • #container: styles the container div with flexbox to align the contents vertically in the center of the page, sets a border, padding, border-radius and background image to it.
  • input[type="file"]: styles the input file element by adding some padding, font size, border and background color to it.
  • #preview-container: sets the width and display to none initially so that the preview image is not visible until the user selects an image.
  • #preview-image: sets the width to 100% and height to auto to maintain aspect ratio of the image.
  • #options-container: styles the options container div with flexbox to arrange the contents vertically in the center of the page, sets the width to 60%.
  • label: styles the label element by setting font size, margin top and colour.


Section 3: Adding JavaScript Functionality

Linking the JavaScript File to the HTML Document

To link the JavaScript file to the HTML document, we need to include the script tag in the body or head section of the HTML document. The script tag includes the source attribute which points to the location of the JavaScript file.


Here's an example of how to link the JavaScript file "script.js" to the HTML document:

<body>

  <!-- HTML content goes here -->

  <script src="script.js"></script>

</body>


Creating the previewImage() Function

The previewImage() function is used to display the selected image when a user selects a file. It takes an event object as an argument, which contains information about the selected file.

Here's an implementation of the previewImage() function:

function previewImage(event) {

  const inputFile = event.target.files[0];

  const previewImage = document.getElementById("preview-image");

  const previewContainer = document.getElementById("preview-container");

 

  if (!inputFile) {

    previewContainer.style.display = "none";

    return;

  }

 

  const reader = new FileReader();

  reader.onload = function (e) {

    previewImage.src = e.target.result;

    previewContainer.style.display = "block";

  };

  reader.readAsDataURL(inputFile);

}


The inputFile variable stores the selected file, the previewImage variable is used to set the src attribute of the img tag, and the previewContainer variable is used to show or hide the preview container. The FileReader() object is used to read the contents of the selected file and set the src attribute of the img tag.


Creating the convertImage() Function

The convertImage() function is used to convert and download the selected image. It uses the Canvas API to convert the image to the selected format.

Here's an implementation of the convertImage() function:

function convertImage() {

  const inputFile = document.getElementById("input-file").files[0];

  const formatSelect = document.getElementById("format-select");

  const format = formatSelect.options[formatSelect.selectedIndex].value;

 

  const canvas = document.createElement("canvas");

  const ctx = canvas.getContext("2d");

  const image = new Image();

  image.src = URL.createObjectURL(inputFile);

  image.onload = function () {

    canvas.width = image.width;

    canvas.height = image.height;

    ctx.drawImage(image00);

    const dataURL = canvas.toDataURL(`image/${format}`);

    const link = document.createElement("a");

    link.href = dataURL;

    link.download = `converted-image.${format}`;

    link.click();

  };

}


The inputFile variable stores the selected file, and the formatSelect variable is used to get the selected format. The canvas variable is used to create a canvas element, and the ctx variable is used to get the 2D rendering context of the canvas. The Image() object is used to create a new image, and the URL.createObjectURL() method is used to create a URL for the selected file.


Once the image is loaded, the canvas width and height are set to match the image size, and the drawImage() method is used to draw the image on the canvas. The toDataURL() method is used to convert the canvas image to a data URL with the selected format, and the createElement() method is used to create a download link. The href and download attributes of the link element are set, and the link is clicked programmatically using the link.click() method. This triggers the download of the converted image file in the selected format.

Here is the full code for the convertImage() function:

function convertImage() {

  const inputFile = document.getElementById("input-file").files[0];

  const formatSelect = document.getElementById("format-select");

  const format = formatSelect.options[formatSelect.selectedIndex].value;

  

  const canvas = document.createElement("canvas");

  const ctx = canvas.getContext("2d");

  const image = new Image();

  image.src = URL.createObjectURL(inputFile);

  image.onload = function () {

    canvas.width = image.width;

    canvas.height = image.height;

    ctx.drawImage(image00);

    const dataURL = canvas.toDataURL(`image/${format}`);

    const link = document.createElement("a");

    link.href = dataURL;

    link.download = `converted-image.${format}`;

    link.click();

  };

}


The Canvas API

The convertImage() function uses the Canvas API to convert the image to the selected format. The Canvas API provides a way to create and manipulate images using JavaScript.

To use the Canvas API, you need to create a canvas element and get its 2D context. The 2D context is an object that provides a set of drawing functions that can be used to draw on the canvas.

In the convertImage() function, we create a new canvas element using the createElement() method, and then get its 2D context using the getContext() method:

const canvas = document.createElement("canvas");

const ctx = canvas.getContext("2d");


We also create a new Image object and set its source to the URL of the selected file using the createObjectURL() method:

const image = new Image();

image.src = URL.createObjectURL(inputFile);


Once the image has loaded, we set the dimensions of the canvas to match the dimensions of the image, and then draw the image on the canvas using the drawImage() method:

image.onload = function () {

  canvas.width = image.width;

  canvas.height = image.height;

  ctx.drawImage(image00);

  // ...

};


Finally, we use the toDataURL() method to convert the canvas to a data URL in the selected format:

const dataURL = canvas.toDataURL(`image/${format}`);


We then create a new a element, set its href attribute to the data URL, set its download attribute to the filename for the converted image, and programmatically click on the link to trigger the download:

const link = document.createElement("a");

link.href = dataURL;

link.download = `converted-image.${format}`;

link.click();


Overall, the Canvas API provides a powerful way to manipulate and convert images using JavaScript.

Conclusion: Building a Simple Image Format Converter with HTML, CSS, and JavaScript

In this tutorial, we have learned how to build a simple image format converter using HTML, CSS, and JavaScript. We started by creating the HTML structure, styling the page with CSS, and linking a JavaScript file to the HTML document. We then created the previewImage() function to display the selected image and the convertImage() function to convert and download the image using the Canvas API.

By following this tutorial, readers have gained a basic understanding of how to use HTML, CSS, and JavaScript to build a simple web application. Readers are encouraged to experiment with their own variations of the code, such as adding more image formats, improving the user interface, or adding more advanced features.

Thank you for following along with this tutorial. If you have any questions or comments, please feel free to reach out to us at https://www.youtube.com/@codelsc.

 

Comments