×

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

Related Topics

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

Javascript Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 minutes read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

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...

3 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.