• Home
  • PHP
  • MySQL
  • Laravel
  • Demos
  • HTML
  • jQuery
  • Framework
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • Advertisement
PHP Lift
  • Home
  • PHP
  • MySQL
  • Laravel
  • Demos
  • HTML
  • jQuery
  • Framework
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Pinterest
    • Youtube
    • Instagram
    • RSS
Javascript Image Compress using HTML5 Canvas & File API before Upload
Home
HTML 5

Javascript Image Compress using HTML5 Canvas & File API before Upload

September 15th, 2025 Huzoor Bux HTML 5, JavaScript 4 comments

Facebook Twitter Google+ LinkedIn Pinterest

In this tutorial, I will show you how to compress images before uploading them to the server. Usually, we don’t compress images and upload them directly to the server. We upload pictures and then squeeze it; in this tutorial, you will learn how to compress images on the client-side and when user upload, it will take less time (if slow internet) and space on the server.

Suppose you upload an image of 5MB. It will decrease its quality and make it 600kb to 700kb if you set rate to 30%. You can try the demo on our website.

javascript compress image

DEMO
DOWNLOAD CODE

I have used the JIC JavaScript Library to perform this task.

Let’s start coding:

HTML Form to upload image and preview:

<div class="container">

	<div class="row">

		<div class="col-md-4 border">

		<form id="upload_form">

			<label for="file">Choose file</label>

			<input type="file" id="fileinput" />

			

		</form>

		</div>

		<div class="col-md-4 border">

			<div class="thumbnail">

				<img id="source_image"  style="width:100%">

				<div class="caption">

					<p>Source Image</p>

					<p><input type="button" id="compress" value="Compress" class="btn-primary" style="display: none;"></p>

				</div>

			</div>

		</div>

		<div class="col-md-4 border">

			<div class="thumbnail">

				<img id="compressed_image"  style="width:100%">

				<div class="caption">

					<p>Compressed Image</p>

					<p><input type="button" id="upload" class="btn-success" value="Upload" style="display: none;"></p>

				</div>

			</div>

		</div>

	</div>

</div>

JavaScript code:

<script>

	var output_format = null;

	var file_name = null;

	function readFile(evt) {

		var file = evt.target.files[0];

		var reader = new FileReader();

	    reader.onload = function(event) {

			var i = document.getElementById("source_image");

			console.log(i);

	            i.src = event.target.result;

	            i.onload = function(){

	                

	                console.log("Image loaded");

	            }

	    };

		output_format = file.name.split(".").pop();

		file_name = file.name;

	    console.log("Filename:" + file.name);

	    console.log("Fileformat:" + output_format);

	    console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");

	    console.log("Type:" + file.type);

	    reader.readAsDataURL(file);

		$("#compress").show();

	    return false;

	}

 // compress image

 	$( "#compress" ).click(function() {

        var source_image = document.getElementById("source_image");

        if (source_image.src == "") {

            alert("You must load an image first!");

            return false;

        }



        var quality = 30;

       	

        console.log("process start...");

        console.log("process start compress ...");

	    compressed_image.src = jic.compress(source_image,quality,output_format).src;

		$("#upload").show();

    	

	});

	// upload imange

	$( "#upload" ).click(function() {

        var compressed_image = document.getElementById("compressed_image");

        if (compressed_image.src == "") {

            alert("You must compress image first!");

            return false;

        }



	    var successCallback= function(response){

            console.log("image uploaded successfully! :)");

            console.log(response);       

        }



        var errorCallback= function(response){

            console.log("image Filed to upload! :)");

            console.log(response); 

        }

    	

    	console.log("process start upload ...");

    	jic.upload(compressed_image, "upload.php", "file", file_name,successCallback,errorCallback);

    	

    });



document.getElementById("fileinput").addEventListener("change", readFile, false);

</script>

It is a simple code to compress images and upload them to a server using PHP.

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook

Related

  • Tags
  • javascript compress image
Facebook Twitter Google+ LinkedIn Pinterest
Next article 3 reasons why you SHOULD write tests
Previous article Free PHP, HTML, CSS, JavaScript/TypeScript editor - CodeLobster IDE

Huzoor Bux

I am a PHP Developer

Related Posts

Const vs. Let vs. Var in Javascript. Which one should you use? JavaScript
September 16th, 2025

Const vs. Let vs. Var in Javascript. Which one should you use?

Sanitizing input with PHP and JavaScript JavaScript
September 15th, 2025

Sanitizing input with PHP and JavaScript

How to show Image before upload JavaScript & HTML5 FileReader() API
September 15th, 2025

How to show Image before upload JavaScript & HTML5 FileReader()

4 Comments

  1. hermawan
    November 3, 2020 at 2:44 am Reply ↓

    maaf ga pakai bahasa inggri. setelah lama nyari ternyata menemukan artikel ini, yang jadi pertanyaan:

    1. bisakah diupload tanpa menekan tombol compress?

    2. bisakah berjalan di browser mobile, seperti browser google chrome di Android?

  2. hermawan
    November 3, 2020 at 3:54 am Reply ↓

    setelah saya coba-coba ini mendekati yang kami inginkan

    makasih atas tutorialnya sangat membantu

    $( “#compress” ).click(function() {

    var source_image = document.getElementById(“source_image”);

    if (source_image.src == “”) {

    alert(“You must load an image first!”);

    return false;

    }

    var quality = 30;

    var successCallback= function(response){

    console.log(“image uploaded successfully! :)”);

    console.log(response);

    }

    var errorCallback= function(response){

    console.log(“image Filed to upload! :)”);

    console.log(response);

    }

    console.log(“process start…”);

    console.log(“process start compress …”);

    source_image.src = jic.compress(source_image,quality,output_format).src;

    jic.upload(source_image, “upload.php”, “file”, file_name,successCallback,errorCallback);

    //$(“#upload”).show();

    });

    // upload imange

    document.getElementById(“fileinput”).addEventListener(“change”, readFile, false);

  3. zam zam
    February 4, 2021 at 4:40 am Reply ↓

    thank you. your code make my day . thumbs up

  4. php
    June 1, 2021 at 8:06 pm Reply ↓

    Wow, the aka “smooth” scrolling on this site was so awful, had to disable JS just for this reason alone.

    Don’t override OS native behaviors folks are used with

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe
Get new posts by email:
Powered by follow.it
Advertisement
Like us
Recent Posts
  • How to Create a Custom Options Page in WordPress?
  • Const vs. Let vs. Var in Javascript. Which one should you use?
  • Examining variable types in PHP
  • 10 Best Food Delivery Apps Systems for Small Restaurants
  • Create Bootstrap form wizard and validation with jQuery
Categories
  • API
  • Bootstrap
  • Bot
  • CSS
  • CSS 3
  • Database
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • Laravel
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • Web 3.0
  • WordPress
Weekly Tags
  • PHP
  • javascript
  • How to
  • laravel
  • css
  • HTML to PDF
  • jQuery
  • api
  • Web Development
  • MYSQL
  • About
  • Privacy Policy
  • Back to top
© PHPLift.net. All rights reserved.