×

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

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 minutes 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 Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes 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 setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes 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 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 Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute 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 Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

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

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.