Image Format Converter for Multiple Files Using HTML, CSS, and JavaScript | CodeLSC


Introduction

Welcome to the documentation for the Image Format Converter, a tool that allows you to convert multiple image files into various formats. In this documentation, we will provide detailed explanations and code snippets for each section of the application.


Preview


HTML Structure

The HTML structure of the Image Format Converter is as follows:

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- ... meta and title tags ... -->
  </head>
  <body>
    <div class="container">
      <h1>CodeLSC | Image Format Converter</h1>
      <input type="file" id="imageInput" multiple />
      <select id="formatSelect">
        <option value="jpeg">JPEG</option>
        <option value="jpg">JPG</option>
        <option value="png">PNG</option>
      </select>
      <button id="convertButton">Convert</button>
      <div id="imagePreview" class="hidden"></div>
      <a id="downloadLink" class="hidden" download="converted_images.zip">Download Converted Images</a>
    </div>
    <!-- ... script tags ... -->
  </body>
</html>


HTML Explanation

  • We have an HTML structure with a container div that includes an input element for selecting multiple image files, a dropdown to choose the desired output format, a "Convert" button to initiate the conversion, an image preview area, and a hidden download link for the zip file.


JavaScript Functionality

The JavaScript code is responsible for the core functionality of the Image Format Converter. Here's a breakdown of the code with corresponding explanations:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
<script>
  const imageInput = document.getElementById('imageInput');
  const formatSelect = document.getElementById('formatSelect');
  const convertButton = document.getElementById('convertButton');
  const imagePreview = document.getElementById('imagePreview');
  const downloadLink = document.getElementById('downloadLink');
 
  // Event listener for the "Convert" button
  convertButton.addEventListener('click', () => {
    const selectedFormat = formatSelect.value;
    const convertedImages = [];
 
    // Loop through the selected image files
    for (let i = 0; i < imageInput.files.length; i++) {
      const file = imageInput.files[i];
      const reader = new FileReader();
 
      reader.onload = function (event) {
        const img = new Image();
        img.src = event.target.result;
        img.onload = function () {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL(`image/${selectedFormat}`);
          convertedImages.push(dataURL);
 
          if (convertedImages.length === imageInput.files.length) {
            imagePreview.innerHTML = '';
            convertedImages.forEach((dataURL, index) => {
              const imgElement = document.createElement('img');
              imgElement.src = dataURL;
              imagePreview.appendChild(imgElement);
            });
 
            const zip = new JSZip();
            for (let i = 0; i < convertedImages.length; i++) {
              zip.file(`image_${i}.${selectedFormat}`, convertedImages[i].split(',')[1], { base64: true });
            }
 
            zip.generateAsync({ type: 'blob' }).then(function (content) {
              downloadLink.href = URL.createObjectURL(content);
              downloadLink.classList.remove('hidden');
            });
          }
        };
      };
 
      reader.readAsDataURL(file);
    }
  });
</script>


JavaScript Explanation

  • We retrieve HTML elements using getElementById.
  • The "Convert" button has an event listener to trigger the conversion process.
  • Inside the event listener, we extract the selected format and prepare an array for storing converted image data.
  • A loop iterates through the selected image files, reads each file, and processes it.
  • We use the HTML5 Canvas API to convert the image to the selected format.
  • Once all images are converted, they are displayed in the image preview area.
  • The code generates a zip file containing the converted images for download.


CSS Styling

The CSS styling makes the application visually appealing and user-friendly. Here's the CSS code with explanations:

body {
  font-family: Arial, sans-serif;
  background-color: #f0f0f0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
 
.container {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  text-align: center;
}
 
h1 {
  color: #0074d9;
  margin-top: 0;
}
 
input,
select,
button {
  margin: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}
 
button {
  background-color: #0074d9;
  color: #fff;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}
 
button:hover {
  background-color: #0056a2;
}
 
#imagePreview {
  margin: 20px 0;
}
 
#imagePreview img {
  max-width: 300px;
  max-height: 300px;
  margin: 10px;
}
 
#downloadLink {
  display: block;
  margin: 20px auto;
  padding: 10px 20px;
  background-color: #0074d9;
  color: #fff;
  text-decoration: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}
 
#downloadLink:hover {
  background-color: #0056a2;
}


CSS Explanation

  • We apply CSS styles to elements for consistent layout and aesthetics.
  • Button styles change on hover for a better user experience.


Conclusion

The Image Format Converter simplifies the task of converting multiple images to different formats. It's a versatile tool that can be customized and enhanced to suit your specific needs. We hope this documentation helps you understand the code and how to use this web application effectively.


Full Code Snippet

Here's the complete HTML code for the Image Format Converter:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>CodeLSC | Image Format Converter</title>
  </head>
  <body>
    <div class="container">
      <h1>CodeLSC | Image Format Converter</h1>
      <input type="file" id="imageInput" multiple />
      <select id="formatSelect">
        <option value="jpeg">JPEG</option>
        <option value="jpg">JPG</option>
        <option value="png">PNG</option>
      </select>
      <button id="convertButton">Convert</button>
      <div id="imagePreview" class="hidden"></div>
      <a id="downloadLink" class="hidden" download="converted_images.zip"
        >Download Converted Images</a
      >
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
    <script>
      const imageInput = document.getElementById('imageInput');
      const formatSelect = document.getElementById('formatSelect');
      const convertButton = document.getElementById('convertButton');
      const imagePreview = document.getElementById('imagePreview');
      const downloadLink = document.getElementById('downloadLink');
 
      convertButton.addEventListener('click', () => {
        debugger;
        const selectedFormat = formatSelect.value;
        const convertedImages = [];
 
        for (let i = 0; i < imageInput.files.length; i++) {
          const file = imageInput.files[i];
          const reader = new FileReader();
 
          reader.onload = function (event) {
            const img = new Image();
            img.src = event.target.result;
            img.onload = function () {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              canvas.width = img.width;
              canvas.height = img.height;
              ctx.drawImage(img, 0, 0);
              const dataURL = canvas.toDataURL(`image/${selectedFormat}`);
              convertedImages.push(dataURL);
 
              if (convertedImages.length === imageInput.files.length) {
                imagePreview.innerHTML = '';
                convertedImages.forEach((dataURL, index) => {
                  const imgElement = document.createElement('img');
                  imgElement.src = dataURL;
                  imagePreview.appendChild(imgElement);
                });
 
                const zip = new JSZip();
                for (let i = 0; i < convertedImages.length; i++) {
                  zip.file(
                    `image_${i}.${selectedFormat}`,
                    convertedImages[i].split(',')[1],
                    { base64: true }
                  );
                }
 
                zip.generateAsync({ type: 'blob' }).then(function (content) {
                  downloadLink.href = URL.createObjectURL(content);
                  downloadLink.classList.remove('hidden');
                });
              }
            };
          };
 
          reader.readAsDataURL(file);
        }
      });
    </script>
  </body>
</html>


Feel free to share this tool with others who may find it valuable for image conversion tasks.

#WebDevelopment #ImageConversion #JavaScript #HTML #CSS

 

Comments