Cloudinary Blog

Cool Tricks for Resizing Images in JavaScript

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 for a Zoom Effect With JS

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.

    Copy to clipboard
    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.

    Copy to clipboard
    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.

Copy to clipboard
<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 Resizing With JS During Image Uploads

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.

Copy to clipboard
<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.

Copy to clipboard
$(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.

Copy to clipboard
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);
    }
  }

Resizing and Rescaling Images Effectively and Speedily With Cloudinary

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.

Automating Smart Cropping

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

Copy to clipboard
cloudinary.imageTag('veducate/skater_2_-_800.jpg', {width: 300, height: 300, gravity: "auto", crop: "crop"}).toHtml();

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:

Ruby:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", :gravity=>"auto:classic", :height=>175, :width=>175, :crop=>"thumb")
PHP v1:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", array("gravity"=>"auto:classic", "height"=>175, "width"=>175, "crop"=>"thumb"))
PHP v2:
Copy to clipboard
(new ImageTag('veducate/spencer-backman-482079-unsplash.jpg'))
  ->resize(Resize::thumbnail()->width(175)->height(175)
    ->gravity(Gravity::autoGravity()
      ->autoFocus(AutoFocus::focusOn(FocusOn::classic()))));
Python:
Copy to clipboard
CloudinaryImage("veducate/spencer-backman-482079-unsplash.jpg").image(gravity="auto:classic", height=175, width=175, crop="thumb")
Node.js:
Copy to clipboard
cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:classic", height: 175, width: 175, crop: "thumb"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().gravity("auto:classic").height(175).width(175).crop("thumb")).imageTag("veducate/spencer-backman-482079-unsplash.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('veducate/spencer-backman-482079-unsplash.jpg', {gravity: "auto:classic", height: 175, width: 175, crop: "thumb"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:classic", height: 175, width: 175, crop: "thumb"})
React:
Copy to clipboard
<Image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <Transformation gravity="auto:classic" height="175" width="175" crop="thumb" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <cld-transformation gravity="auto:classic" height="175" width="175" crop="thumb" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="veducate/spencer-backman-482079-unsplash.jpg" >
  <cl-transformation gravity="auto:classic" height="175" width="175" crop="thumb">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Gravity("auto:classic").Height(175).Width(175).Crop("thumb")).BuildImageTag("veducate/spencer-backman-482079-unsplash.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().gravity("auto:classic").height(175).width(175).crop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setGravity("auto:classic").setHeight(175).setWidth(175).setCrop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg")!, cloudinary: cloudinary)
g_auto:classic Transformation Applied to It g_auto:classic
Ruby:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", :gravity=>"auto:backpack", :height=>175, :width=>175, :crop=>"thumb")
PHP v1:
Copy to clipboard
cl_image_tag("veducate/spencer-backman-482079-unsplash.jpg", array("gravity"=>"auto:backpack", "height"=>175, "width"=>175, "crop"=>"thumb"))
PHP v2:
Copy to clipboard
(new ImageTag('veducate/spencer-backman-482079-unsplash.jpg'))
  ->resize(Resize::thumbnail()->width(175)->height(175)
    ->gravity(Gravity::autoGravity()
      ->autoFocus(AutoFocus::focusOn(FocusOn::backpack()))));
Python:
Copy to clipboard
CloudinaryImage("veducate/spencer-backman-482079-unsplash.jpg").image(gravity="auto:backpack", height=175, width=175, crop="thumb")
Node.js:
Copy to clipboard
cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:backpack", height: 175, width: 175, crop: "thumb"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().gravity("auto:backpack").height(175).width(175).crop("thumb")).imageTag("veducate/spencer-backman-482079-unsplash.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('veducate/spencer-backman-482079-unsplash.jpg', {gravity: "auto:backpack", height: 175, width: 175, crop: "thumb"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("veducate/spencer-backman-482079-unsplash.jpg", {gravity: "auto:backpack", height: 175, width: 175, crop: "thumb"})
React:
Copy to clipboard
<Image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <Transformation gravity="auto:backpack" height="175" width="175" crop="thumb" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="veducate/spencer-backman-482079-unsplash.jpg" >
  <cld-transformation gravity="auto:backpack" height="175" width="175" crop="thumb" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="veducate/spencer-backman-482079-unsplash.jpg" >
  <cl-transformation gravity="auto:backpack" height="175" width="175" crop="thumb">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Gravity("auto:backpack").Height(175).Width(175).Crop("thumb")).BuildImageTag("veducate/spencer-backman-482079-unsplash.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().gravity("auto:backpack").height(175).width(175).crop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setGravity("auto:backpack").setHeight(175).setWidth(175).setCrop("thumb")).generate("veducate/spencer-backman-482079-unsplash.jpg")!, cloudinary: cloudinary)
backback g_auto:backpack

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

Creating Photo Collages

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).

Ruby:
Copy to clipboard
cl_image_tag("yellow_tulip.jpg", :transformation=>[
  {:width=>220, :height=>140, :crop=>"fill"},
  {:overlay=>"brown_sheep", :width=>220, :height=>140, :x=>220, :crop=>"fill"},
  {:overlay=>"horses", :width=>220, :height=>140, :y=>140, :x=>-110, :crop=>"fill"},
  {:overlay=>"white_chicken", :width=>220, :height=>140, :y=>70, :x=>110, :crop=>"fill"},
  {:overlay=>"butterfly.png", :height=>200, :x=>-10, :angle=>10}
  ])
PHP v1:
Copy to clipboard
cl_image_tag("yellow_tulip.jpg", array("transformation"=>array(
  array("width"=>220, "height"=>140, "crop"=>"fill"),
  array("overlay"=>"brown_sheep", "width"=>220, "height"=>140, "x"=>220, "crop"=>"fill"),
  array("overlay"=>"horses", "width"=>220, "height"=>140, "y"=>140, "x"=>-110, "crop"=>"fill"),
  array("overlay"=>"white_chicken", "width"=>220, "height"=>140, "y"=>70, "x"=>110, "crop"=>"fill"),
  array("overlay"=>"butterfly.png", "height"=>200, "x"=>-10, "angle"=>10)
  )))
PHP v2:
Copy to clipboard
(new ImageTag('yellow_tulip.jpg'))
  ->resize(Resize::fill()->width(220)->height(140))
  ->overlay(
      Overlay::source(Source::image('brown_sheep')
        ->transformation((new ImageTransformation())
          ->resize(Resize::fill()->width(220)->height(140))))
      ->position((new Position())
        ->offsetX(220)))
    ->overlay(
        Overlay::source(Source::image('horses')
          ->transformation((new ImageTransformation())
            ->resize(Resize::fill()->width(220)->height(140))))
        ->position((new Position())
          ->offsetX(-110)->offsetY(140)))
          ->overlay(
              Overlay::source(Source::image('white_chicken')
                ->transformation((new ImageTransformation())
                  ->resize(Resize::fill()->width(220)->height(140))))
              ->position((new Position())
                ->offsetX(110)->offsetY(70)))
            ->overlay(
                Overlay::source(Source::image('butterfly')
                  ->format(Format::png())
                  ->transformation((new ImageTransformation())
                    ->rotate(Rotate::byAngle(10))
                    ->resize(Resize::scale()->height(200))))
                ->position((new Position())
                  ->offsetX(-10)
              
            
              
            ));
Python:
Copy to clipboard
CloudinaryImage("yellow_tulip.jpg").image(transformation=[
  {'width': 220, 'height': 140, 'crop': "fill"},
  {'overlay': "brown_sheep", 'width': 220, 'height': 140, 'x': 220, 'crop': "fill"},
  {'overlay': "horses", 'width': 220, 'height': 140, 'y': 140, 'x': -110, 'crop': "fill"},
  {'overlay': "white_chicken", 'width': 220, 'height': 140, 'y': 70, 'x': 110, 'crop': "fill"},
  {'overlay': "butterfly.png", 'height': 200, 'x': -10, 'angle': 10}
  ])
Node.js:
Copy to clipboard
cloudinary.image("yellow_tulip.jpg", {transformation: [
  {width: 220, height: 140, crop: "fill"},
  {overlay: "brown_sheep", width: 220, height: 140, x: 220, crop: "fill"},
  {overlay: "horses", width: 220, height: 140, y: 140, x: -110, crop: "fill"},
  {overlay: "white_chicken", width: 220, height: 140, y: 70, x: 110, crop: "fill"},
  {overlay: "butterfly.png", height: 200, x: -10, angle: 10}
  ]})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation()
  .width(220).height(140).crop("fill").chain()
  .overlay(new Layer().publicId("brown_sheep")).width(220).height(140).x(220).crop("fill").chain()
  .overlay(new Layer().publicId("horses")).width(220).height(140).y(140).x(-110).crop("fill").chain()
  .overlay(new Layer().publicId("white_chicken")).width(220).height(140).y(70).x(110).crop("fill").chain()
  .overlay(new Layer().publicId("butterfly.png")).height(200).x(-10).angle(10)).imageTag("yellow_tulip.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('yellow_tulip.jpg', {transformation: [
  {width: 220, height: 140, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("brown_sheep"), width: 220, height: 140, x: 220, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("horses"), width: 220, height: 140, y: 140, x: -110, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("white_chicken"), width: 220, height: 140, y: 70, x: 110, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("butterfly.png"), height: 200, x: -10, angle: 10}
  ]}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("yellow_tulip.jpg", {transformation: [
  {width: 220, height: 140, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("brown_sheep"), width: 220, height: 140, x: 220, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("horses"), width: 220, height: 140, y: 140, x: -110, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("white_chicken"), width: 220, height: 140, y: 70, x: 110, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("butterfly.png"), height: 200, x: -10, angle: 10}
  ]})
React:
Copy to clipboard
<Image publicId="yellow_tulip.jpg" >
  <Transformation width="220" height="140" crop="fill" />
  <Transformation overlay="brown_sheep" width="220" height="140" x="220" crop="fill" />
  <Transformation overlay="horses" width="220" height="140" y="140" x="-110" crop="fill" />
  <Transformation overlay="white_chicken" width="220" height="140" y="70" x="110" crop="fill" />
  <Transformation overlay="butterfly.png" height="200" x="-10" angle="10" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="yellow_tulip.jpg" >
  <cld-transformation width="220" height="140" crop="fill" />
  <cld-transformation :overlay="brown_sheep" width="220" height="140" x="220" crop="fill" />
  <cld-transformation :overlay="horses" width="220" height="140" y="140" x="-110" crop="fill" />
  <cld-transformation :overlay="white_chicken" width="220" height="140" y="70" x="110" crop="fill" />
  <cld-transformation :overlay="butterfly.png" height="200" x="-10" angle="10" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="yellow_tulip.jpg" >
  <cl-transformation width="220" height="140" crop="fill">
  </cl-transformation>
  <cl-transformation overlay="brown_sheep" width="220" height="140" x="220" crop="fill">
  </cl-transformation>
  <cl-transformation overlay="horses" width="220" height="140" y="140" x="-110" crop="fill">
  </cl-transformation>
  <cl-transformation overlay="white_chicken" width="220" height="140" y="70" x="110" crop="fill">
  </cl-transformation>
  <cl-transformation overlay="butterfly.png" height="200" x="-10" angle="10">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation()
  .Width(220).Height(140).Crop("fill").Chain()
  .Overlay(new Layer().PublicId("brown_sheep")).Width(220).Height(140).X(220).Crop("fill").Chain()
  .Overlay(new Layer().PublicId("horses")).Width(220).Height(140).Y(140).X(-110).Crop("fill").Chain()
  .Overlay(new Layer().PublicId("white_chicken")).Width(220).Height(140).Y(70).X(110).Crop("fill").Chain()
  .Overlay(new Layer().PublicId("butterfly.png")).Height(200).X(-10).Angle(10)).BuildImageTag("yellow_tulip.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation()
  .width(220).height(140).crop("fill").chain()
  .overlay(new Layer().publicId("brown_sheep")).width(220).height(140).x(220).crop("fill").chain()
  .overlay(new Layer().publicId("horses")).width(220).height(140).y(140).x(-110).crop("fill").chain()
  .overlay(new Layer().publicId("white_chicken")).width(220).height(140).y(70).x(110).crop("fill").chain()
  .overlay(new Layer().publicId("butterfly.png")).height(200).x(-10).angle(10)).generate("yellow_tulip.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation()
  .setWidth(220).setHeight(140).setCrop("fill").chain()
  .setOverlay("brown_sheep").setWidth(220).setHeight(140).setX(220).setCrop("fill").chain()
  .setOverlay("horses").setWidth(220).setHeight(140).setY(140).setX(-110).setCrop("fill").chain()
  .setOverlay("white_chicken").setWidth(220).setHeight(140).setY(70).setX(110).setCrop("fill").chain()
  .setOverlay("butterfly.png").setHeight(200).setX(-10).setAngle(10)).generate("yellow_tulip.jpg")!, cloudinary: cloudinary)
collage

Copy to clipboard
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();

Cropping With Custom Shapes

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:

Ruby:
Copy to clipboard
cl_image_tag("pasta.png", :transformation=>[
  {:width=>173, :height=>200, :crop=>"fill"},
  {:overlay=>"hexagon_sample", :flags=>"cutter"}
  ])
PHP v1:
Copy to clipboard
cl_image_tag("pasta.png", array("transformation"=>array(
  array("width"=>173, "height"=>200, "crop"=>"fill"),
  array("overlay"=>"hexagon_sample", "flags"=>"cutter")
  )))
PHP v2:
Copy to clipboard
(new ImageTag('pasta.png'))
  ->resize(Resize::fill()->width(173)->height(200))
  ->reshape(Reshape::cutByImage(Source::image('hexagon_sample')));
Python:
Copy to clipboard
CloudinaryImage("pasta.png").image(transformation=[
  {'width': 173, 'height': 200, 'crop': "fill"},
  {'overlay': "hexagon_sample", 'flags': "cutter"}
  ])
Node.js:
Copy to clipboard
cloudinary.image("pasta.png", {transformation: [
  {width: 173, height: 200, crop: "fill"},
  {overlay: "hexagon_sample", flags: "cutter"}
  ]})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation()
  .width(173).height(200).crop("fill").chain()
  .overlay(new Layer().publicId("hexagon_sample")).flags("cutter")).imageTag("pasta.png");
JS:
Copy to clipboard
cloudinary.imageTag('pasta.png', {transformation: [
  {width: 173, height: 200, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: "cutter"}
  ]}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("pasta.png", {transformation: [
  {width: 173, height: 200, crop: "fill"},
  {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: "cutter"}
  ]})
React:
Copy to clipboard
<Image publicId="pasta.png" >
  <Transformation width="173" height="200" crop="fill" />
  <Transformation overlay="hexagon_sample" flags="cutter" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="pasta.png" >
  <cld-transformation width="173" height="200" crop="fill" />
  <cld-transformation :overlay="hexagon_sample" flags="cutter" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="pasta.png" >
  <cl-transformation width="173" height="200" crop="fill">
  </cl-transformation>
  <cl-transformation overlay="hexagon_sample" flags="cutter">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation()
  .Width(173).Height(200).Crop("fill").Chain()
  .Overlay(new Layer().PublicId("hexagon_sample")).Flags("cutter")).BuildImageTag("pasta.png")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation()
  .width(173).height(200).crop("fill").chain()
  .overlay(new Layer().publicId("hexagon_sample")).flags("cutter")).generate("pasta.png");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation()
  .setWidth(173).setHeight(200).setCrop("fill").chain()
  .setOverlay("hexagon_sample").setFlags("cutter")).generate("pasta.png")!, cloudinary: cloudinary)
hexagon

Copy to clipboard
cloudinary.imageTag('pasta.png', {transformation: [
  {width: 173, height: "200", crop: fill},
  {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: cutter},
  ]}).toHtml();

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

Ruby:
Copy to clipboard
cl_image_tag("pasta.png", :overlay=>"hexagon_sample", :flags=>["cutter", "relative"], :width=>1.0, :height=>1.0)
PHP v1:
Copy to clipboard
cl_image_tag("pasta.png", array("overlay"=>"hexagon_sample", "flags"=>array("cutter", "relative"), "width"=>"1.0", "height"=>"1.0"))
PHP v2:
Copy to clipboard
(new ImageTag('pasta.png'))
  ->reshape(
      Reshape::cutByImage(Source::image('hexagon_sample')
        ->transformation((new ImageTransformation())
          ->resize(Resize::scale()->width(1.0)->height(1.0)
            ->relative()
  ))));
Python:
Copy to clipboard
CloudinaryImage("pasta.png").image(overlay="hexagon_sample", flags=["cutter", "relative"], width="1.0", height="1.0")
Node.js:
Copy to clipboard
cloudinary.image("pasta.png", {overlay: "hexagon_sample", flags: ["cutter", "relative"], width: "1.0", height: "1.0"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().overlay(new Layer().publicId("hexagon_sample")).flags("cutter", "relative").width(1.0).height(1.0)).imageTag("pasta.png");
JS:
Copy to clipboard
cloudinary.imageTag('pasta.png', {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: ["cutter", "relative"], width: "1.0", height: "1.0"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("pasta.png", {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: ["cutter", "relative"], width: "1.0", height: "1.0"})
React:
Copy to clipboard
<Image publicId="pasta.png" >
  <Transformation overlay="hexagon_sample" flags={["cutter", "relative"]} width="1.0" height="1.0" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="pasta.png" >
  <cld-transformation :overlay="hexagon_sample" flags={["cutter", "relative"]} width="1.0" height="1.0" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="pasta.png" >
  <cl-transformation overlay="hexagon_sample" flags={{["cutter", "relative"]}} width="1.0" height="1.0">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Overlay(new Layer().PublicId("hexagon_sample")).Flags("cutter", "relative").Width(1.0).Height(1.0)).BuildImageTag("pasta.png")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().overlay(new Layer().publicId("hexagon_sample")).flags("cutter", "relative").width(1.0).height(1.0)).generate("pasta.png");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setOverlay("hexagon_sample").setFlags("cutter", "relative").setWidth(1.0).setHeight(1.0)).generate("pasta.png")!, cloudinary: cloudinary)
relative

Copy to clipboard
cloudinary.imageTag('pasta.png', {transformation: [
  {overlay: new cloudinary.Layer().publicId("hexagon_sample"), flags: cutter:relative, width: 1.0, height: 1.0}
  ]}).toHtml();

Learning More About Cloudinary

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.

Checking Out the Details of CSS Image Transformations

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

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more