JavaScript Compress Image

Pictures have been a fundamental and widely used element of modern websites and web applications since the inception of the internet. Images play a crucial role in conveying information and concepts, complementing written content to improve comprehension.

Aside from improving user experience, images can also help reinforce a brand's identity by providing additional context or clarification on various website subjects. Furthermore, they play a crucial role in a website's search engine optimization (SEO), which can boost user interaction, attract more traffic, and ultimately improve conversion rates.

In modern online applications, there is a high volume of image uploads and downloads. However, transferring files between the client and server can quickly become resource-heavy. It is important to consider that a large portion of Internet traffic comes from mobile devices, which means users are likely to upload high-resolution images taken with their phones. Due to the constantly improving camera resolutions in new mobile devices, these image files can be very large, exceeding 10MB in size.

When users share photographs on your platform, other users download those photos for various uses once they are uploaded to your storage server. Comparatively speaking then this job requires a lot more resources than adding a new entry to the database. We should anticipate paying more for:

  • Upload bandwidth.
  • Bandwidth downloads. For every image posted, several downloads are often in a use case.
  • Storage: Data and photos are usually kept on a disc or in an object storage service. It's crucial to remember that, unless you establish a deletion policy, once you save a photo to your storage, you must keep it there for the duration of the program. Because of this, storage prices never go down over time, unlike bandwidth charges, which are based on consumption at any one moment.
  • How can one optimize the sharing of images?

Utilizing image compression emerges as a clear remedy. However, this approach may not be suitable if the primary concern of your software lies in maintaining high image quality. Opting for server-side compression is a prevalent strategy that reduces the required storage space and download bandwidth. While this technique may be more cost-effective than download bandwidth, it does incur additional expenses in terms of increased CPU cycles.

Another approach to reduce unnecessary upload data is by compressing images on the client's side before sending them over the network. This can be achieved using modern browser APIs. Compressing images locally takes less time compared to uploading a large file, thus not only saving bandwidth but also speeding up the upload process.

The HTML5 features such as Canvas, FileReader, and Blob enable the compression of images within the browser, leading to a reduction in the number of bytes required for uploading, saving, and downloading operations on the platform.

A brief overview of the MDN background

JavaScript enables the creation of graphics through the Canvas API which works in conjunction with the HTML element. This technology finds applications in various tasks including real-time video processing, data visualization, gaming graphics, animation, and photo editing. The Canvas API primarily focuses on 2D graphics. In contrast, the WebGL API leverages the element to produce hardware-accelerated 2D and 3D graphics.

In web development, web applications have the capability to asynchronously access files or raw data buffers stored on the user's device by leveraging the FileReader object. To identify the specific file or data to be accessed, developers utilize File or Blob objects. File objects can be obtained through the mozGetAsFile interface on an HTMLCanvasElement, extracted from a FileList object generated when a user uploads files through the element, or acquired from the DataTransfer object during a drag-and-drop interaction.

A blob is a fixed, unchangeable data entity that mimics a file. It can be interpreted as either text or binary data, or it can be converted into a ReadableStream to enable the utilization of its functions for data manipulation. Blobs are useful for representing data that may not always conform to the JavaScript native format. Building upon the Blob concept, the File interface expands on Blob's functionalities to manage files stored on the user's device.

Why image optimization is necessary?

Optimizing images is a method employed to provide users with high-quality images in the correct format, size, and resolution, all while minimizing the file size. This approach is especially beneficial for websites that showcase high-quality images to visitors without impacting key performance indicators like page loading speed.

Code:

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example for image compression in JavaScript</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
  <h2>Image Compression Example</h2>
  <input type="file" id="imageFile" accept="image/*">
  <br>
  <button onclick="compressImage()">Compress your image here</button>
  <br>
  <img id="result" src="#" alt="Result">
</div>

<script src="https://placehold.co/300x300/3498db/ffffff?text=Sample+Image"></script>
</body>
</html>

CSS Code

Example

body {
  font-family: Calibri;
  background-color: pink;
  padding: 10px;
}

.container {
  max-width: 400px;
  margin: auto;
  text-align: center;
  background-color: grey;
  padding: 10px;
  border-radius: 3px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

button {
  background-color: lightblue;
  color: black;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  border-radius: 4px;
  margin-top: 8px;
}

button:hover {
  background-color: none;
}

img {
  max-width: 100%;
  height: auto;
  margin-top: 20px;
}

JavaScript Code

Example

function compressImage() {
  const fileInput = document.getElementById('imageFile');
  const img = document.getElementById('result');

  const reader = new FileReader();
  reader.onload = function(e) {
    const imgObj = new Image();
    imgObj.onload = function() {
      const MAX_WIDTH = 300; // Max width for the resulted image
      const MAX_HEIGHT = 300; // Max height for the resulted image
      let width = imgObj.width;
      let height = imgObj.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }

      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(imgObj, 0, 0, width, height);

      const compressedDataURL = canvas.toDataURL('image/jpeg', 0.5); // Adjust quality as we need (0.0 - 1.0)
      img.src = compressedDataURL;
      img.style.display = 'block';
    };
    imgObj.src = e.target.result;
  };
  reader.readAsDataURL(fileInput.files[0]);
}

Output

Initially, the first step involves selecting the option that says "Please upload your image."

Next, it is necessary to select the desired image for upload and then proceed to click on the "Open" button.

Next, the following screen will be displayed, allowing us to adjust the dimensions of the image to our preference, such as modifying the width, height, and quality of the picture. Subsequently, we will be able to proceed with downloading the customized image.

Upon right-clicking on the image, a pop-up menu will appear, allowing us to select the "save as" option in order to download and save the image to our device.

Input Required

This code uses input(). Please provide values below: