Build a Javascript Image Compressor using HTML5 Canvas & File API Before Uploading to Server Full Project For Beginners

Build a Javascript Image Compressor using HTML5 Canvas & File API Before Uploading to Server Full Project For Beginners

 

Welcome folks today in this blog post we will be building a javascript image compressor using html5 canvas and file api before uploading to server. 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" onchange="previewFile()"><br>
<img id="source_img" src="" height="200" alt="Image preview...">
<br>
<button onclick="myFunction()" >compress</button>
<img id="target_img" src="" height="200" alt="Image preview...">
</body>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jic/2.0.2/JIC.min.js"></script>
 <script src="script.js"></script>
</html>

 

 

And now make a script.js file inside the root directory and copy paste the below code

See also  JavaScript Program to Loop Through an Object Using For Loop Full Project For Beginners

 

script.js

 

function previewFile() {
      var preview = document.querySelector('img');
      var file    = document.querySelector('input[type=file]').files[0];
      var reader  = new FileReader();
    
      reader.addEventListener("load", function () {
        preview.src = reader.result;
          
      }, false);
    
      if (file) {
        reader.readAsDataURL(file);
      }
    }
    
    function myFunction(){
        var source_img = document.getElementById("source_img"),
            target_img = document.getElementById("target_img");
        var quality =  60,
        output_format = 'jpg';
        target_img.src = jic.compress(source_img,quality,output_format).src;
        console.log("I am a myFunction!");
    };

 

 

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

 

Leave a Reply