Build a Image Compressor and Optimizer in Javascript Without Losing Quality Full Project For Beginners

Build a Image Compressor and Optimizer in Javascript Without Losing Quality Full Project For Beginners

 

Welcome folks today in this blog post we will be building a image compressor and optimizer in javascript without losing quality. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

index.html

 

<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Javascript Image Compressor</title>
</head>
<body>
    <input type="file" name="upload-image" id="upload-image" required />
    <p name="before-compression"></p>
    <p name="after-compression"></p>
    <img src="" class="before" style="display:none;"/>
    <canvas style="display: none;"></canvas>
    <img src="" class="after" style="display:none;"/>
</body>
 <script src="script.js"></script>
</html>

 

See also  Build a Dragalia Lost – Dojo Upgrade Material Calculator in Browser Using HTML5 CSS3 and Javascript Full Project For Beginners

 

Now make a script.js file inside the root directory and copy paste the following code

 

script.js

 

const ReadAndCompress = (e) => {
    const size = `Before Compression: ${(e.target.files[0].size/(1000*1024)).toFixed(2)} MB`;
    document.querySelector("p[name=before-compression]").innerHTML = size;
    const reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
  
    reader.onload = event => {
      const img = document.querySelector("img.before");
      img.src = event.target.result;
      //img.style = "display: true";
      img.onload = () => {
        const width = img.width;
        const height = img.height;
        const elem = document.querySelector('canvas');
        elem.width = width;
        elem.height = height;
        const ctx = elem.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);
        const webp = ctx.canvas.toDataURL("image/webp", 0.5);
        const imgAfter = document.querySelector("img.after");
        imgAfter.src = webp;
        imgAfter.style = "display:true";
        const head = 'data:image/webp;base64,';
        const imgFileSize = (Math.round((webp.length - head.length)*3/4) / (1000)).toFixed(2);
        document.querySelector("p[name=after-compression]").innerHTML =
          `After Compression: ${imgFileSize} KB`;
      },
      reader.onerror = error => console.error(error);
    }
  }
  
  document.querySelector("input[name=upload-image]")
  .addEventListener("change", (event) => ReadAndCompress(event))

 

See also  Smoke.js - Javascript Library for Making Alert Boxes

 

And now if you open index.html file you will see the below screenshot

 

 

 

As you can see it has reduced the size of the image from 1.23MB to27.56KB

 

Leave a Reply