Skip to content

Cool Tricks for Resizing Images in JavaScript

Resizing images with JavaScript (JS) creates nifty effects, many of which you cannot do in Cascading Style Sheets (CSS). However, even though you can automate a zoom effect with JS to enable users to zoom in and out of images, limitations abound.

This article shows you how to resize images in JavaScript for a zoom effect and do the same much faster and more effectively in Cloudinary, with which you can also apply many other appealing effects. Examples are scaling with percentage values and scaling widths of up to 140 percent of the original. Be assured that you’ll be impressed.

Here are the topics:

Resizing images with JS is particularly useful for creating online product galleries, in which users can zoom in or out of images according to the maximum settings you specify with only one click.

The resizing task takes two functions, which you can either insert directly into your HTML source with <script> tags or into a standalone JS file. Those functions work for any <img> tag that you label with the ID zoom_img. See this full demo of the code.

The two functions are as follows:

  • zoomin(), which creates a zoom-in action for scaling up the image size by 100 pixels until the maximum defined size (1000 px.) is reached.

    function zoomin(){
        var myImg = document.getElementById("zoom_img");
        var currWidth = myImg.clientWidth;
        if(currWidth >= 1000){
            alert("You’re fully zoomed in!");
        } else{
            myImg.style.width = (currWidth + 100) + "px";
        } 
    }
    
  • zoomout(), which creates a zoom-out action for scaling down the image by 100 pixels until the minimum defined size (50 px.) is reached.

    function zoomout(){
        var myImg = document.getElementById("zoom_img");
        var currWidth = myImg.clientWidth;
        if(currWidth >= 50){
            alert("That’s as small as it gets.");
        } else{
            myImg.style.width = (currWidth - 100) + "px";
        }
    }
    

To enable users to call those functions, create an interface (see below) with buttons for the image. Add them above or below the image element in your HTML file.

<button type="button" onclick="zoomin()"><img src="/examples/images/zoom-in.png"> Zoom In</button>

<button type="button" onclick="zoomout()"><img src="/examples/images/zoom-out.png"> Zoom Out</button>

For more details on resizing images with CSS, see Image Resizing: Manually With CSS and Automatically With Cloudinary.

Automating the resizing task is ideal for enabling users to resize images in JavaScript or for resizing them with a built-in mechanism before being stored away. An example of the code in this section is on CodePen.

To start, build the HTML framework into which to load, preview, and transform your images. The following code creates an input to accept images, a button to enable resizing, and two placeholders for your original and resized images.

<input id="imageFile" name="imageFile" type="file" class="imageFile" accept="image/*"/> 
<input type="button" value="Resize Image" 
onclick="resizeImage()"/> 
<br/>
<img src="" id="preview">
<img src="" id="output">

Next, create a function to accept the images:

Note:

The code below is in jQuery. Be sure to link or refer to the jQuery library.

$(document).ready(function() {
  $("#imageFile").change(function(event) {
    var files = event.target.files;
    var file = files[0];

    if (file) {
      var reader = new FileReader();
      reader.onload = function(e) {
        document.getElementById("preview").src = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  });
});

Finally, create a resizing function (see below) within which to load the image into the file reader, set the image to be resized, create a canvas for resizing, and output the resized image. Note the boldfaced comments for each of the steps.

function resizeImage() {
 var filesToUploads = document.getElementById("imageFile").files;
  var file = filesToUploads[0];
    if (file) {
      var reader = new FileReader();
      
// Set the image for the FileReader
      reader.onload = function (e) {
        var img = document.createElement("img");
        img.src = e.target.result;

// Create your canvas
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 500;
        var MAX_HEIGHT = 500;
        var width = img.width;
        var height = img.height;

// Add the resizing logic
        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;
          }
        }

//Specify the resizing result
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        dataurl = canvas.toDataURL(file.type);
        document.getElementById("output").src = dataurl;
      };
      reader.readAsDataURL(file);
    }
  } 

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, apply built-in effects, filters, and modifications, including automated image rotations that are difficult or impossible to produce with CSS and JS.

Also with Cloudinary, you can easily transform images programmatically with SDKs or URL parameters. Cloudinary applies changes dynamically, leaving your original images intact. That means you can modify images on the fly as your site design evolves and as you support more devices and screen sizes—a huge convenience and time saver.

Below are three faster and easier ways in which to resize images in JavaScript with Cloudinary. All you need to do is add parameters to the URL.

With Cloudinary, you can automatically crop images to the right size through content-aware AI. During the process, you can automatically select faces, individual features, or areas of interest by applying the gravity filter (g).

The g_auto settings in this example automatically crop the most interesting area, as determined by AI:

auto gravity

cloudinary.imageTag('veducate/skater_2_-_800.jpg', {width: 300, height: 300, gravity: "auto", crop: "crop"}).toHtml();
Code language: JavaScript (javascript)

You can also specify areas to preserve with smart cropping. A use case is to ensure that the model doesn’t take center stage in product images. This example specifies the backpack as the area of focus:

Loading code examples g_auto:classic Transformation Applied to It g_auto:classic Loading code examples backback g_auto:backpack

cloudinary.imageTag('veducate/spencer-backman-482079-unsplash.jpg', {width: 175, height: 175, gravity: "auto:backpack", crop: "thumb"}).toHtml();
Code language: JavaScript (javascript)

Photo collages are fun. By combining the overlay (o) and crop (c) parameters, you can collect images in any order and embellish them with text or filters.

The example below adds images to the collage with the desired size (w and h attributes), position (x and y attributes), crop mode (c attribute), and angle of rotation (`av attribute).

Loading code examples collage

cloudinary.imageTag('yellow_tulip.jpg', {transformation: [
  {width: 220, height: 140, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("brown_sheep"), width: 220, height: 140, crop: "fill", x: 220},
  {overlay: new cloudinary.Layer().publicId("horses"), width: 220, height: 140, crop: "fill", y: 140, x: -110},
  {overlay: new cloudinary.Layer().publicId("white_chicken"), width: 220, height: 140, crop: "fill", y: 70, x: 110},
  {overlay: new cloudinary.Layer().publicId("butterfly"), height: 200, x: -10, angle: 10}
  ]}).toHtml();
Code language: JavaScript (javascript)

By cropping images into custom shapes, you can fit them in any space. Simply apply the overlay parameter as a mask and the flag (f in the URL) parameter.

To set things up, specify the final image size, define the mask and the related function, and specify the source image, like this:

Loading code examples hexagon

cloudinary.imageTag('pasta.png', {transformation: [
  {width: 173, height: "200", crop: “fill”},
  {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: “cutter”},
  ]}).toHtml();
Code language: JavaScript (javascript)

Adding the relative parameter matches the mask to the proportions you desire, as in this example:

Loading code examples relative

cloudinary.imageTag('pasta.png', {transformation: [
  {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: “cutter:relative”, width: 1.0, height: 1.0}
  ]}).toHtml();
Code language: JavaScript (javascript)

Besides the capability for image resizing, Cloudinary offers a multitude of robust tools for web developers, including the following:

  • Automated image uploads. You can upload images at scale anywhere from a browser, mobile app, or application back-end directly to the cloud.
  • Generous image storage. Cloudinary accords you up to 25 GB free managed, secure, and cloud-based storage space with multiregion backup, revision history, and disaster recovery.
  • Seamless asset management. You can efficiently manage your image library on Cloudinary by performing tasks like searching, organizing, and tagging files; controlling access; and monitoring usage and performance.
  • Effective image transformation. You can transform, enhance, transcode, crop, scale, and enhance images with a URL-based API or with SDKs that support all popular programming languages.
  • Automated image optimization. Cloudinary automatically selects the optimal quality and encoding settings for images, adapts the settings to any resolution or pixel density, and scales or crops images to focus on the important regions.
  • Responsive images. Cloudinary automatically scales images in an art-directed manner, cropping them to fit different resolutions and viewports.
  • Reliable and fast image delivery. Cloudinary delivers images through Content Delivery Networks (CDNs)—Akamai, Fastly, and CloudFront—with no integration or management on your part.

Do give Cloudinary a try. To start, sign up for a free account.

Want to learn more about CSS image transformations? These articles are an excellent resource:

Back to top

Featured Post