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

推荐订阅源

V
Vulnerabilities – Threatpost
T
The Blog of Author Tim Ferriss
S
SegmentFault 最新的问题
D
DataBreaches.Net
博客园_首页
罗磊的独立博客
B
Blog
T
Threat Research - Cisco Blogs
C
Cisco Blogs
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
G
GRAHAM CLULEY
H
Help Net Security
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
SecWiki News
SecWiki News
T
Threatpost
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Schneier on Security
Schneier on Security
T
The Exploit Database - CXSecurity.com
Google Online Security Blog
Google Online Security Blog
T
Tor Project blog
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Y
Y Combinator Blog
H
Hacker News: Front Page
V
V2EX
Security Latest
Security Latest
Cloudbric
Cloudbric
Simon Willison's Weblog
Simon Willison's Weblog
Attack and Defense Labs
Attack and Defense Labs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
NISL@THU
NISL@THU
S
Secure Thoughts
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
V2EX - 技术
V2EX - 技术
Vercel News
Vercel News
P
Palo Alto Networks Blog
IT之家
IT之家
MyScale Blog
MyScale Blog
有赞技术团队
有赞技术团队
Application and Cybersecurity Blog
Application and Cybersecurity Blog
D
Docker
Google DeepMind News
Google DeepMind News
Webroot Blog
Webroot Blog

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 Hopscotch built India's largest online Kids' fashion brand with ImageKit Dropbox Vs. DAM: Which Is The Right Tool For Digital Asset Management Digital Asset Management for Photographers: A Complete Guide Why digital asset management for agencies is essential Helping both Top and Bottom Line: SaffronStays rapid, profitable growth with ImageKit How KreditBee simplified media experiences with ImageKit Google Drive alternatives for businesses (with fast-growing teams) Node.js image upload ImageKit: The Secret Ingredient in Swiggy’s Expansion Journey Streamlining the Design Approval Process: A Comprehensive Guide AV1 Codec - Complete guide for video application devs PHP image and video upload Angular image & video upload AV1 vs VP9: Which codec should you choose? Adding video player in Next.js React Video Player VP8 vs VP9 - In the context of online video delivery Exploring WebM vs MP4 7 Free Digital Asset Management Software that are not Open-Source Comparing 9 Top Digital Asset Management Tools in the Market What are Brand Standards and Why do they Matter? Boost Sales and Brand Appeal: Essential Tips for eCommerce Image Management Brand Recall: The Strategy to Create Unforgettable Brands How to upload files in HTML? Branding for Small Businesses (2025 Edition) Everything you need to know about VP9 codec Recent updates from ImageKit and what's next Best Ways to Write RFP For Digital Asset Management (+ with free RFP template) What is Brand Dilution? How to Avoid It? Explained with [Examples] The Importance of Brand Identity: Leveraging Digital Asset Management for Impact From Launch to Scale: How to Launch a Brand Campaign Digital Asset Management Requirements - What do You Need to Evaluate and How? Marketing Collateral Management: A Quick End-to-End Guide Video Content Management System: What Is It And How To Choose One? Dropbox vs. Google Drive vs. Onedrive: The Best Cloud Storage Solution How to Build Brand Trust: Get Started In 2025 Google Drive vs. Box: A Detailed Comparison How Digital Asset Management Solutions Help Protect Brand Equity A DAM Solution Can Safeguard Your Digital Intellectual Property - Here’s How WebP Vs. PNG: Which Image Format Should You Use and Why? How to Resize Images in Bootstrap Easily Progressive jpegs (PJPEG): the key to loading images faster on your website Dropbox vs. Google Drive: The Best Cloud Storage For Digital Assets Dropbox Pros & Cons In 2024: An In-Depth Analysis and Why A DAM Solution Stands Out Google Drive Vs OneDrive: The Better Storage Option For Digital Assets Manage your video assets better with video metadata Understanding DAM's Role in Strengthening Brand Identity Digital asset management strategy: What to know before creating one The Ultimate Guide To Marketing Agency Onboarding 6 Solutions To Simplify Large File Sharing Over The Web A Step-by-Step Breakdown of a Video Production Workflow 13 Digital Asset Management Use Cases You Should Know How to Conduct a Brand Audit and Manage Your Brand Assets Costly Consequences of Inconsistent Branding And How DAM Can Help Dynamic Asset Transformation: What It Is, Why You Need It, and How ImageKit Can Help Everything You Need to Know About HTML Video Autoplay How To Select Your DAM Vendor: A Complete Guide How to Boost User Experience with Smart Digital Asset Management React Image Optimization: A Guide for Web Developers Why Should DAM Be A Part Of Your MarTech Stack? Unleashing the Power of Content Repurposing with ImageKit MKV vs MP4: Which Video File Format Is Better for Your Needs? Digital Asset Management For Ecommerce: A Complete Guide How an Image Tagging Software can Transform Your Image Search How to Manage Your Content Lifecycle Effectively M4V vs MP4: Which Video Format Should You Use and Why? Why Every Business Needs An Image Management System All The Questions To Ask During A Dam Demo Which is the Best Image Format for Your Website? Uploading Multiple Files Using JavaScript: A Comprehensive Guide
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.