×

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

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.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 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 input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 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 Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

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.

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.

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 Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes 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 Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 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 radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

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

Javascript Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.