Jul 10, 2024

How Meta Platforms Handle Image Resize & Compression: Optimizing Image Resize and Compression with JavaScript Techniques

Learn why social media platforms compress images before uploading and discover techniques to efficiently resize and compress images for your applications, enhancing speed and user experience.

Author

Subhajit DeySubhajit DeySenior Software Engineer - III
How Meta Platforms Handle Image Resize & Compression: Optimizing Image Resize and Compression with JavaScript Techniques

We often notice that on every platform where image uploads are needed, the images are compressed before being uploaded. Popular social media platforms like Instagram, Facebook, and WhatsApp compress images before uploading them. But why do they do this, and how can we achieve the same?

The primary reason for compressing images is to reduce the file size, which helps in faster uploads and downloads. Smaller file sizes also save server storage space and reduce bandwidth usage, making the platform more efficient and cost-effective. Additionally, compressed images load faster for users, improving the overall user experience.

Here, you will learn different techniques for resizing and compressing images before uploading. Each technique has unique pros and cons, and you will discover which technique to use in your application based on your needs.

Prerequisites

<label
    style="height: 300px; width: 100%"
    class="my-auto d-flex text-center align-center justify-center v-card rounded cursor-pointer border-md border-primary border-dashed rounded-lg text-primary">
    <input hidden type="file" accept="image/*" :capture="false" @change="(e) => uploadFile(e)" />
    <div
      class="d-flex align-center justify-center flex-column text-body-2 text-text-tertiary image-compressor image-compressor-expanded"
    >
        <v-icon size="100">mdi-cloud-upload</v-icon>
        <p>Drag and drop or click here<br />to upload image.</p>
    </div>
</label>

In the frontend, it will look something like this:

We call this uploadFile function from the UI whenever there is any change in the input file.

const uploadFile = e => {
    const file = e.target.files && e.target.files[0]
    if (file) {
      // handleFileInputChange(file) 
      // we are going to use handleFileInputChange for our examples
    }
    e.target.value = ''
}

Techniques

Now you might be wondering what the techniques are. So, let's go through it.

  1. Using canvas API .toDataURL() method.
  2. Using canvas API .toBlob() method.
  3. Using third party external library Pica.
  4. Using third library compress.js.

Let's understand it one by one:
NOTES: We are considering resizing and compression of image. (In every implementation we have maxWidth=1200 and maxHeight=1200, and imageQuality=0.8)

canvas API .toDataURL():

Introduction

The toDataURL(type, encoderOptions) method of the Canvas API allows us to convert the image in the canvas to a data URL. The encoderOptions parameter can specify the image quality, with a value between 0 and 1, for formats that support lossy compression.

Implementation

const handleFileInputChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const img = new Image();
    img.src = e.target.result;
    img.onload = () => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      const maxWidth = 1200,
        maxHeight = 1200;
      let { width, height } = img;
      if (width > height && width > maxWidth) {
        height = (height * maxWidth) / width;
        width = maxWidth;
      } else if (height > maxWidth) {
        width = (width * maxHeight) / height;
        height = maxHeight;
      }
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0, width, height);

      const compressedBase64 = canvas.toDataURL("image/jpeg", 0.8); //assinging imageQuality
      imageUrl.value = compressedBase64;
      // compressedBase64 is base64 string of compressed image.
      // service call or emit function to make service call
    };
  };
  reader.readAsDataURL(file);
};

Pros

  • Provides a blob object, which is useful for file uploads and further processing.
  • Control over image quality.

Cons

  • Slightly more complex than toDataURL.
  • Similar performance limitations as toDataURL for large images.

Pica:

Introduction

Pica is a high-quality image resizing library for Canvas that also supports image compression. You can use the resize method to resize images and either pica.toBlob or canvas.toBlob to compress the image.

Implementation

const handleFileInputChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const img = new Image();
    img.src = e.target.result;
    img.onload = async () => {
      const canvas = document.createElement("canvas");
      const maxWidth = 1200,
            maxHeight = 1200;
      let { width, height } = img;
      if (width > height && width > maxWidth) {
        height = (height * maxWidth) / width;
        width = maxWidth;
      } else if (height > maxHeight) {
        width = (width * maxHeight) / height;
        height = maxHeight;
      }
      canvas.width = width;
      canvas.height = height;

      // Create a temporary canvas to hold the original image
      const tempCanvas = document.createElement("canvas");
      tempCanvas.width = img.width;
      tempCanvas.height = img.height;
      const tempCtx = tempCanvas.getContext("2d");
      tempCtx.drawImage(img, 0, 0);

      // Use pica to resize the image
      await pica.resize(tempCanvas, canvas);

      // Convert the resized canvas to a blob and then to a file
      pica.toBlob((blob) => {
        const compressedFile = new File([blob], file.name, { type: 'image/jpeg' });
        // handle the compressed file (e.g., upload, display, etc.)
        console.log(compressedFile);
      }, 'image/jpeg', 0.8); // Adjust the quality as needed
    };
  };
  reader.readAsDataURL(file);
};

Pros

  • Fast and efficient image resizing.
  • High-quality resizing algorithms.
  • Easy to integrate and use.

Cons

  • Requires adding an external library.
  • The bundle size is slightly larger due to the library.

compress.js:

Introduction


compress.js is a library that provides high-level abstraction for resizing and compressing images. It balances ease of use and functionality.

Implementation

const handleFileInputChange = async (file) => {
  const compress = new Compress();

  const files = [file]; // Array of files to compress
  const options = {
    size: 1, // max size in MB
    quality: 0.8, // quality of the image
    maxWidth: 1200, // max width of the output image
    maxHeight: 1200, // max height of the output image
    resize: true, // enable resizing
  };

  const output = await compress.compress(files, options);
  const { data, ext } = output[0]; // compressed image data and extension
  const compressedBase64 = `data:image/${ext};base64,${data}`;

  // Convert the base64 to a File object if needed
  const blob = Compress.convertBase64ToFile(compressedBase64);
  const compressedFile = new File([blob], file.name, { type: `image/${ext}` });
  imageFile.value = compressedFile;
};

Pros

  • High level of abstraction and ease of use.
  • Includes both resizing and compression.
  • Good balance between image quality and file size.

Cons

  • Adding an external library increases the project size.
  • Might not support all image formats natively.

These are some ways to handle image compression and resizing images. Let me know in the comments if I forgot to add any methods for resize and compression.

Conclusion

Choosing the right method for image compression and resizing in JavaScript depends on your specific requirements and constraints; for simplicity and minimal setup: Use canvas.toDataURL if you only need a base64 string, or canvas.toBlob if you need a Blob object.
For better performance and quality: Use Pica if you are dealing with large images and need high-quality resizing or Compress.js if you want an easy-to-use library that handles both resizing and compression effectively

  • Canvas API to DataURL():
    • Simple and straightforward.
    • Provides control over image quality.
    • Suitable for moderate image sizes but can be slow for larger images.
  • Canvas API to Blob():
    • Produces a Blob object, ideal for file uploads.
    • Offers control over image quality.
    • Slightly more complex than to DataURL but has similar performance limitations for large images.
  • Pica:
    • High-quality and efficient image resizing.
    • Easy to use with powerful algorithms.
    • Requires an external library, which increases bundle size.
  • Compress.js:
    • High level of abstraction with ease of use.
    • Combines both resizing and compression effectively.
    • Requires an external library, which may not support all image formats natively.

Key Takeaways:

  • Simplicity vs. Control: The canvas.toDataURL() and canvas.toBlob() methods are easy to implement and provide control over the image quality. However, they might not be the most efficient for large images.
  • Performance: For high-performance needs, especially with large images, using a specialized library like Pica can provide better results with high-quality resizing and compression.
  • Ease of UseCompress.js offers a simple and comprehensive solution for both resizing and compressing images but comes with the trade-off of adding an external library.
  • Blob Handling: Methods that produce Blob objects (toBlob and pica) are particularly useful when dealing with file uploads and further processing on the server side.
  • Library Overhead: While external libraries provide advanced functionalities and ease of use, they increase the overall bundle size of your project, which might be a consideration for performance-sensitive applications.

By understanding these methods' strengths and weaknesses, you can make an informed decision on the best approach for your image processing needs in JavaScript.

Subscribe to Our Newsletter

RELATED ARTICLES

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
A real-world look at how oversized images can trigger Safari reloads and iOS crashes in Flutter apps and how smarter image decoding prevents them.
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
This blog explores how Flutter Agent Skills improve AI-assisted development by combining official framework workflows with project-specific guidance for more consistent development.
Why Everything Your AI Builds Looks the Same
Why Everything Your AI Builds Looks the Same
This blog explores why AI-generated interfaces often look alike and explains how design systems, product context, and reusable engineering practices help teams build distinctive, scalable
How We Built the Missing Bridge from Code to Figma
Technology

Jul 10, 2026

How We Built the Missing Bridge from Code to Figma
This blog explores how AI-generated React apps get turned into fully editable, designer-ready Figma files by reading React Fiber instead of the DOM.
Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
Technology

Jun 27, 2026

Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
A practical breakdown of building resilient AWS-to-on-premises connectivity with WireGuard HA, active-standby failover, and deep packet-forwarding observability.
We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
Technology

Jun 19, 2026

We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
A practical guide to building a 114-second multi-cloud disaster recovery failover between AWS and Azure — what we built, what broke, and what we learned.
Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
Technology

Jun 12, 2026

Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
This blog explains how organizations can balance speed, scalability, and operational flexibility as they grow from startup to enterprise scale.

The Right Conversation Can Save You Six Months.

Whether you’re navigating AI adoption, modernizing legacy systems, or scaling a product - we start by listening. No pitch deck. No template. A real conversation.