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

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.

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 Use: Compress.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

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform
Oct 12, 2026

How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform

This blog explains how a real-time sports platform uses synchronous, asynchronous, and scheduled processing paths to handle rewards without slowing down the player experience.

Insight
Building an MCP-Powered QA Agent

Building an MCP-Powered QA Agent

Build an MCP QA agent that runs Playwright tests, validates APIs, and analyzes failures through a controlled, auditable tool layer with human approval.

Insight
From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline
Oct 9, 2026

From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline

This blog explains how an AI-assisted Playwright pipeline can analyze test failure evidence, identify probable root causes, and support human-validated debugging.

Insight
The Model Context Protocol: From First Call to Production
Oct 8, 2026

The Model Context Protocol: From First Call to Production

This blog explains how Model Context Protocol (MCP) works, from tool discovery and execution to OAuth authorization, security controls, and production deployment.

Insight
Stop Automating Everything: A Balanced Quality Engineering Approach to Testing
Oct 8, 2026

Stop Automating Everything: A Balanced Quality Engineering Approach to Testing

Balanced quality engineering places automation, API testing, exploratory work, and AI where each gives the most value, so teams ship faster without trading away user-perceived quality.

Insight
From Rolling Deployments to Zero-Downtime Releases
Oct 6, 2026

From Rolling Deployments to Zero-Downtime Releases

This blog explains how Blue-Green deployment helps reduce downtime in online banking releases through traffic switching, pod readiness, static-resource versioning, and rapid rollback.

Insight
The Deprecation Notice Nobody Reads
Oct 5, 2026

The Deprecation Notice Nobody Reads

This blog explains why API deprecation notices often fail and how staged retirement, telemetry, brownouts, and scheduled enforcement can make API migrations more controlled and predictable.

Footer

The Right Conversation Can

Save You Six Months.

Book a Call