惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
博客园 - Franky
J
Java Code Geeks
V
Visual Studio Blog
G
Google Developers Blog
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Stack Overflow Blog
Stack Overflow Blog
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
博客园 - 【当耐特】
IT之家
IT之家
I
InfoQ
U
Unit 42
C
Check Point Blog
Martin Fowler
Martin Fowler

ImageKit.io Blog

Next.js Image Optimization with ImageKit Use Video as a Background in Your Next.js Project How to Fix Autoplay Video in Next.js How Durian Scaled a Visual-First Retail Experience to 350K Monthly Visitors Online How Matsmart accelerated image delivery across countries with ImageKit AI in Digital Asset Management: From Smart Workflows to Agentic Automation How Joseph Joseph unified and secured global video delivery with ImageKit How Modall powers fast, effortless media delivery across 40+ projects with ImageKit Digital Asset Management (DAM) Trends: 2026 Report How to add a poster image to Video.js player (and automate it) HLS streaming with Video.js + React Building the future of storytelling with fast, AI-powered video delivery How PushOwl delivers 100M+ image-rich notifications seamlessly with ImageKit How Homify delivers millions of interior design images seamlessly with ImageKit Better event discovery with lightning‑fast videos & images Adding video player in React Native Video player in Angular applications Crop and resize videos in React Next.js image and video upload React image and video upload React video optimization How we quadrupled our traffic to 625K monthly page views How Apollo 24|7 boosted performance & reduced costs with ImageKit Simplify your media workflows with ImageKit DAM integrations Extending Lighthouse for custom image and video optimization analysis Brand Asset Management: What is it? How does it work? WordPress Digital Asset Management Guide - Manage your WP media assets better Why Shopify retailers need a digital asset management solution DAM vs. SharePoint: Which is best for you? AI-powered Metadata and Tagging in Digital Asset Management
How to resize images in Javascript?
Manu Chaudhary · 2021-07-06 · via ImageKit.io Blog

Image resizing is computationally expensive and usually done on the server-side so that right-sized image files are delivered to the client-side. This approach also saves data while transmitting images from the server to the client.

However, there are a couple of situations where you might need to resize images purely using JavaScript on the client side. For example -

  1. Resizing images before uploading to server

    Uploading a large file on your server will take a lot of time. You can first resize images on the browser and then upload them to reduce upload time and improve application performance.

  2. Rich image editors that work on client-side

    A rich image editor that offers image resize, crop, rotation, zoom IN and zoom OUT capabilities often require image manipulation on the client-side. The speed is critical for the user in these editors.

    If a user is manipulating a heavy image, it will take a lot of time to download transformed images from the server. Imagine this with operations like undo/redo and complex text and image overlays.

Image manipulation in JavaScript is done using the canvas element. There are libraries like fabric.js that offer rich APIs.

Apart from the above two reasons, in almost all cases, you would want to get the resized images from the backend itself so that client doesn't have to deal with heavy processing tasks.

In this post-

  1. We will first talk about how to do resizing purely in JavaScript using the canvas element.

  2. Then we will cover in great detail how you can resize, crop, and do a lot with images by changing the image URL in the src attribute. This is the preferred way to resize images without degrading the user experience programmatically.

    Also, we will learn how you can do this without needing to set up any libraries or backend servers.

Image resizing in JavaScript - Using canvas element

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. Resizing images in browser using canvas is relatively simple.

drawImage function allows us to render and scale images on canvas element.

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

The first argument image can be created using the Image() constructor, as well as using any existing <img> element.

Let's write the code to resize a user-uploaded image on the browser side 300x300.

<html>

<body>
    <div>
        <input type="file" id="image-input" accept="image/*">
        <img id="preview"></img>
    </div>

    <script>
        let imgInput = document.getElementById('image-input');
        imgInput.addEventListener('change', function (e) {
            if (e.target.files) {
                let imageFile = e.target.files[0];
                var reader = new FileReader();
                reader.onload = function (e) {
                    var img = document.createElement("img");
                    img.onload = function (event) {
                        // Dynamically create a canvas element
                        var canvas = document.createElement("canvas");

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

                        // Actual resizing
                        ctx.drawImage(img, 0, 0, 300, 300);

                        // Show resized image in preview element
                        var dataurl = canvas.toDataURL(imageFile.type);
                        document.getElementById("preview").src = dataurl;
                    }
                    img.src = e.target.result;
                }
                reader.readAsDataURL(imageFile);
            }
        });
    </script>
</body>

</html>

Let's understand this in parts. First, the input file type field in HTML

<html>
  <body>
    <div>
      <input type="file" id="image-input" accept = "image/*">
      <img id="preview"></img>
    </div>
  </body>
</html>

Now we need to read the uploaded image and create an img element using Image() constructor.

let imgInput = document.getElementById('image-input');
imgInput.addEventListener('change', function (e) {
    if (e.target.files) {
        let imageFile = e.target.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var img = document.createElement("img");
            img.onload = function(event) {
                // Actual resizing
            }
            img.src = e.target.result;
        }
        reader.readAsDataURL(imageFile);
    }
});

Finally, let's draw the image on canvas and show preview element.

// Dynamically create a canvas element
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");

// Actual resizing
ctx.drawImage(img, 0, 0, 300, 300);

// Show resized image in preview element
var dataurl = canvas.toDataURL(imageFile.type);
document.getElementById("preview").src = dataurl;

You might notice that the resized image looks distorted in a few cases. It is because we are forced 300x300 dimensions. Instead, we should ideally only manipulate one dimension, i.e., height or width, and adjust the other accordingly.

All this can be done in JavaScript, since you have access to input image original height (img.width) and width using (img.width).

For example, we can fit the output image in a container of 300x300 dimension.

var MAX_WIDTH = 300;
var MAX_HEIGHT = 300;

var width = img.width;
var height = img.height;

// Change the resizing logic
if (width > height) {
    if (width > MAX_WIDTH) {
        height = height * (MAX_WIDTH / width);
        width = MAX_WIDTH;
    }
} else {
    if (height > MAX_HEIGHT) {
        width = width * (MAX_HEIGHT / height);
        height = MAX_HEIGHT;
    }
}

var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);

Controlling image scaling behavior

Scaling images can result in fuzzy or blocky artifacts. There is a trade-off between speed and quality. By default browsers are tuned for better speed and provides minimum configuration options.

You can play with the following properties to control smoothing effect:

ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;

Image resizing in JavaScript - The serverless way

ImageKit allows you to manipulate image dimensions directly from the image URL and get the exact size or crop you want in real-time. Start with a single master image, as large as possible, and create multiple variants from the same.

For example, we can create a 400 x 300 variant from the original image like this:

https://ik.imagekit.io/ikmedia/ik_ecom/shoe.jpeg?tr=w-400,h-300
Image resized to 400x300px (enlarged for representation here) using real-time transformations
Image resized to 400x300px (enlarged for representation here) using real-time transformations

You can use this URL directly on your website or app for the product image, and your users get the correct image instantly.

Image resizing using URL
Image resizing using URL

If you don't want to crop the image while resizing, there are several possible crop modes.

https://ik.imagekit.io/ikmedia/ik_ecom/shoe.jpeg?tr=w-400,h-300,cm-pad_resize,bg-F5F5F5
Compared to the previous transformation, the output image here has more grey padding around all its edges.
Compared to the previous transformation, the output image here has more grey padding around all its edges.

We have published guides on how you can do the following things using ImageKit's real-time image manipulation.

Summary

  • In most cases, you should not do image resizing in the browser because it is slow and results in poor quality. Instead, you should use an image CDN like ImageKit.io to resize images dynamically by changing the image URL. Try our forever free plan today!

  • If your use-case demands client-side resizing, it is possible using the canvas element.