JavaScirpt Tutorial Index

JavaScript Tutorial Javascript Example Javascript comment Javascript Variable Javascript Data Types Javascript Operators Javascript If Else Javascript Switch Statement Javascript loop JavaScript Function Javascript Object JavaScript Arrays Javascript String Javascript Date Javascript Math Javascript Number Javascript Dialog Box Javascript Window Object Javascript Document Object Javascript Event Javascript Cookies Javascript getElementByID Javascript Forms Validation Javascript Email Validation Javascript Password Validation Javascript Re-Password Validation Javascript Page Redirect Javascript Print How to Print a Page Using JavaScript Textbox events in JavaScript How to find the largest number contained in a JavaScript Array?

Misc

JavaScript P5.js JavaScript Minify JavaScript redirect URL with parameters Javascript Redirect Button JavaScript Ternary Operator JavaScript radio button checked value JavaScript moment date difference Javascript input maxlength JavaScript focus on input Javascript Find Object In Array JavaScript dropdown onchange JavaScript Console log Multiple variables JavaScript Time Picker Demo JavaScript Image resize before upload Functional Programming in JavaScript JavaScript SetTimeout() JavaScript SetInterval() Callback and Callback Hell in JavaScript Array to String in JavaScript Synchronous and Asynchronous in JavaScript Compare two Arrays in JavaScript Encapsulation in JavaScript File Type Validation while Uploading Using JavaScript or jquery Convert ASCII Code to Character in JavaScript Count Character in string in JavaScript Get First Element of Array in JavaScript How to convert array to set in JavaScript How to get current date and time in JavaScript How to Remove Special Characters from a String in JavaScript Number Validation in JavaScript Remove Substring from String in JavaScript

Interview Questions

JavaScript Interview Questions JavaScript Beautifier Practice Javascript Online Object in JavaScript JavaScript Count HTML Interpreter Getters and Setters in JavaScript Throw New Error in JavaScript XOR in JavaScript Callbacks and Promises in JavaScript Atob in JavaScript Binary in JavaScript Palindrome Number in JavaScript How to Get First Character Of A String In JavaScript How to Get Image Data in JavaScript How to get URL in JavaScript JavaScript GroupBy Methods difference-between-var-let-and-const-keyword-in-java-script

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the image resizing is done on the client-side using JavaScript.

Why are images resized before uploading to the server?

Uploading a large file on the server takes a lot of time. So, it's advisable to first resize the images on the browser and then upload them. It reduces the upload time and improves the application performance of the website.

Imagine an image editor with the feature to resize, crop, rotate, zoom in and zoom out the image, but it often requires image manipulation at the client side.

But while editing the image, efficiency and speed are important for the user in these editors.

After the image manipulation is done, it takes quite a time to download transformed images from the server.

How is image resizing done using JavaScript?

The canvas() element is used in JavaScript for image manipulation. Although, there are various libraries available that can help us do so, for example, fabric.js (it has good APIs).

What is <canvas> tag?

This element acts as the only container for graphics. The other functionalities of JavaScript are used to draw the graphics.

The <canvas> element is primarily used to draw graphics via JavaScript. This element consists of several methods for drawing lines, boxes, circles, text, and adding images.

This method is supported by mostly all the browsers like Google chrome, safari, Microsoft Edge/Internet Explorer, Oracle, Firefox etc.

The <canvas> tag usually draws a rectangular area on an HTML page. By default, a <canvas> element provides no border and no content.

Syntax:

<canvas id= “nameofId” width= “value" height= "value"></canvas>

Example:

<!DOCTYPE html>
<html>
<head>
    <title>
         Javascript resize images
    </title>
</head>


<body>


<canvas id="samplebox" width="300" height="200" style="border:2px solid red;">
The canvas tag is not supported in this browser.
</canvas>


</body>
</html>

Output:

JavaScript Image resize before upload

Image resizing in JavaScript

The drawImage function is used along with “src” attributes on the images. This function allows us to render and scale images on the canvas element.

Syntax:

drawImage(image, x, y, width, height)

Here, the “image” is created using <img> element tag alomg with the image() constructor.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>
         Javascript Resizing Images while uploading
    </title>
</head>




<body>
    <div>
    <p>Upload any image by clicking on the button. The image will be resized to the dimensions of 400*350</p>
        <input type="file" id="image-upload" accept="image/*">
        <img id="img-content"></img>
    </div>


    <script>
        let imgupload = document.getElementById('image-upload');
        imgupload.addEventListener('change', function (e) {
            if (e.target.files) {
                let imageVal = e.target.files[0];
                var reader = new FileReader();
                reader.onload = function (e) {
                    var img = document.createElement("img");
                    img.onload = function (event) {
                        // This line is dynamically creating a canvas element
                        var canvas = document.createElement("canvas");


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


                        //This line shows the actual resizing of image
                        ctx.drawImage(img, 0, 0, 400, 350);


                        //This line is used to display the resized image in the body
                        var url = canvas.toDataURL(imageVal.type);
                        document.getElementById("img-content").src = url;
                    }
                    img.src = e.target.result;
                }
                reader.readAsDataURL(imageVal);
            }
        });
    </script>
</body>


</html>

Here, the following example demonstrates how to resize an image(uploaded by the user) to the dimensions of  400X350.

Output:

JavaScript Image resize before upload

After uploading the following image from the local device,

JavaScript Image resize before upload

Now the screen looks like this,

JavaScript Image resize before upload