JavaScript Base image transformations (Beta)

Overview

After you or your users have uploaded image assets to Cloudinary, you can deliver them via dynamic URLs. You can include instructions in your dynamic URLs that tell Cloudinary to transform your assets using a set of transformation parameters. All transformations are performed automatically in the cloud and your transformed assets are automatically optimized before they are routed through a fast CDN to the end user for optimal user experience.

For example, you can resize and crop, add overlay images, blur or pixelate faces, apply a large variety of special effects and filters, and apply settings to optimize your images and to deliver them responsively.

The cloudinary-js-base library simplifies the generation of transformation URLs, and include special components and directives for easy embedding of assets in your JavaScript application.

If you haven't yet installed the JavaScript SDK v2, you might want to jump to the quickstart guide first.

See also: JavaScript Base video transformations

Syntax overview

The JavaScript SDK v2 provides an intuitive coding experience for transforming an asset:

  • The SDK supports an action-based syntax, designed to make building delivery URLs and transformations logical and discoverable.
  • It allows discovering the available options from within your development environment, and ensures that only options that are supported can be used together.

The general form of the syntax is:

SDK2 transformation general syntax

An example being:

SDK2 transformation structure

Actions and ActionGroups

  • Assets expose methods called ActionGroups (myImage.adjust()) that represent a directive to Cloudinary on how to transform a specific aspect of an asset
  • ActionGroups receive an Action object as a parameter that defines the specific action to apply
  • Action objects are created through Factory methods (Adjust.replaceColor())
  • Some actions require a qualifier as a parameter (Color.LIGHTBLUE)
  • You can find more Actions in @cloudinary/base/actions
  • You can import all actions with import {Actions} from '@cloudinary/base'

Qualifiers and QualifierValues

  • Actions expose methods to define their behaviors (tolerance())
  • We call the methods on Actions, Qualifiers
  • Qualifiers usually accept a QualifierValue (17 in tolerance(17))
  • QualifierValues can be primitive (numbers, strings) or predefined SDK values that can be imported
  • Many QualifierValues are functions
  • You can find more QualifierValues in @cloudinary/base/qualifiers

The output of each ActionGroup is a complete transformation component (separated by slashes) in the URL. For example, the syntax example above would generate the following URL:

Transformed sample image

Tree shaking

The JavaScript SDK v2 allows you to import only what you need, to minimize your bundle size.

For example, if you import Effect, you import all effect actions, which may be more than you need. The only reason you may want to do this is to make other methods discoverable. Without tree shaking, actions require qualification (for example, Effect.outline()).

  • Without tree shaking:

    Copy to clipboard
    import {Effect} from "@cloudinary/base/actions/effect";
    
    // Effect.outline()

    You can also use:

    Copy to clipboard
    import {Effect} from "@cloudinary/base/actions/effect";
    const {outline} = Effect;
    
    // outline()

    In this case outline() is equivalent to Effect.outline().

  • With tree shaking:

    Copy to clipboard
    import {outline} from '@cloudinary/base/actions/effect';
    
    // outline()

Similarly, for qualifier values:

  • Without tree shaking:

    Copy to clipboard
    import {OutlineMode} from "@cloudinary/base/qualifiers/outlineMode";
    
    // OutlineMode.outer()
  • With tree shaking:

    Copy to clipboard
    import {outer} from "@cloudinary/base/qualifiers/outlineMode";
    
    // outer()

Most of the examples shown in this guide use tree shaking.

Deliver and transform images

The JavaScript SDK v2 makes it easy for you to create image URLs including any transformation parameters.

Direct URL building

You can build an image URL by:

  1. Configuring your Cloudinary instance.
  2. Instantiating a CloudinaryImage object for the image you want to deliver, using cld.image().
  3. Calling the toURL() method of the CloudinaryImage object to return the delivery URL:
Copy to clipboard
import {Cloudinary} from "@cloudinary/base";

// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
}); 

// Instantiate a CloudinaryImage object for the image with public ID, 'sample'.
const myImage = cld.image('sample');

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

The resulting URL, myURL, is:

Sample image

Specifying a version of your image to deliver

You can specify a particular version of your image to deliver by using the setVersion method. The version is added to the delivery URL as explained in Asset versions.

For example, to specify version 1610625835 of the sample image from the example above:

Copy to clipboard
myImage.setVersion(1610625835);

The resulting URL is now:

Transforming your image

Images are transformed by adding serialized transformation instructions to the image delivery URL. For example, to scale your image to a width of 400 pixels, add c_scale,w_400.

https://res.cloudinary.com/demo/image/upload/c_scale,w_400/sample.jpg

Using the cloudinary-js-base library, you transform an image by performing one or more transformation actions on the CloudinaryImage object (see the syntax overview). Remember to import the actions that you are using:

Copy to clipboard
import {Cloudinary} from "@cloudinary/base";

// Import the scale mode from the resize action.
import {scale} from "@cloudinary/base/actions/resize";

// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
}); 

// Use the image with public ID, 'sample'.
const myImage = cld.image('sample');

// Scale the image to a width of 400 pixels.
myImage.resize(scale().width(400));

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

Chaining transformations

Cloudinary transformations can be chained together (each transformation is applied to the result of the previous transformation). For example, the following code crops the image to 150x150, rounds the corners, applies a sepia effect, adds text to the top center of the resized image, then rotates the entire result by 20 degrees and delivers a PNG.

Copy to clipboard
import {Cloudinary} from "@cloudinary/base";

// Import required actions.
import {fill} from "@cloudinary/base/actions/resize";
import {source} from "@cloudinary/base/actions/overlay";
import {format} from "@cloudinary/base/actions/delivery";
import {byAngle} from "@cloudinary/base/actions/rotate"
import {sepia} from "@cloudinary/base/actions/effect";
import {byRadius} from "@cloudinary/base/actions/roundCorners";

// Import required values.
import {png} from "@cloudinary/base/qualifiers/format";
import {text} from "@cloudinary/base/qualifiers/source";
import {Position} from "@cloudinary/base/qualifiers/position";
import {north} from "@cloudinary/base/qualifiers/compass";
import {TextStyle} from "@cloudinary/base/qualifiers/textStyle";


// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
}); 

// Use the image with public ID, 'sample'.
const myImage = cld.image('sample');

// Transform the image.
myImage
  .resize(fill(150, 150))
  .roundCorners(byRadius(20))
  .effect(sepia())
  .overlay(   
    source(
      text('This is my picture', new TextStyle('arial',18))
      .textColor('white')      
    )
    .position(new Position().gravity(compass(north())).offsetY(20)))
  .rotate(byAngle(20))
  .delivery(format(png()));

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

The code above generates the following image delivery URL:

Transformed image

Apply common image transformations using cloudinary-js-base

This section provides an overview and examples of the following commonly used image transformation features, along with links to more detailed documentation on these features:

Keep in mind that this section is only intended to introduce you to the basics of using image transformations with the cloudinary-js-base library.

For comprehensive explanations of how to implement a wide variety of transformations, see Image transformations. For a full list of all supported image transformations and their usage, see the Transformation URL API reference.

Resizing and cropping

There are a variety of different ways to resize and/or crop your images, and to control the area of the image that is preserved during a crop. The following example uses the fill cropping method to generate and deliver an image that completely fills the requested 250x250 size while retaining the original aspect ratio. It uses face detection gravity to ensure that all the faces in the image are retained and centered when the image is cropped:

Copy to clipboard
import {Cloudinary} from "@cloudinary/base";
import {fill} from "@cloudinary/base/actions/resize";
import {faces} from "@cloudinary/base/qualifiers/focusOn";
import {focusOn} from "@cloudinary/base/qualifiers/gravity";

// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
});

// Use the image with public ID, 'family_bench'.
const myImage = cld.image('family_bench');

// Apply the transformation.
myImage.resize(fill().width(250).height(250).gravity(focusOn(faces())));

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();
Original image before face recognition cropping Original image Fill cropping with 'faces' gravity Fill cropping with 'faces' gravity

For details on all resizing and cropping options, see resizing and cropping images.

Converting to another image format

You can deliver any image uploaded to Cloudinary in essentially any image format. There are three main ways to convert and deliver in another format:

  • Specify the image's public ID with the desired extension.
  • Explicitly set the desired format using the format action type of the delivery action.
  • Use auto format to instruct Cloudinary to deliver the image in the most optimized format for each browser that requests it.

For example:

To deliver a .jpg file in .gif format:

  • Either add the .gif extension to the public ID when instantiating the CloudinaryImage:

    Copy to clipboard
    import {Cloudinary} from "@cloudinary/base"
    
    // Create and configure your Cloudinary instance.
    const cld = new Cloudinary({
      cloud: {
        cloudName: 'demo'
      }
    }); 
    
    // Use the image with public ID, 'sample', specifying the 'gif' extension.
    const myImage = cld.image('sample.gif');
    
    // Render the image in an 'img' element.
    const imgElement = document.createElement('img');
    imgElement.src = myImage.toURL();

    This is the returned URL:

  • Or use the delivery action, setting format to GIF:

    Copy to clipboard
    import {Cloudinary} from "@cloudinary/base";
    import {gif} from "@cloudinary/base/qualifiers/format";
    import {format} from "@cloudinary/base/actions/delivery";
    
    // Create and configure your Cloudinary instance.
    const cld = new Cloudinary({
      cloud: {
        cloudName: 'demo'
      }
    }); 
    
    // Use the image with public ID, 'sample'.
    const myImage = cld.image('sample');
    
    // Set the format to GIF.
    myImage.delivery(format(gif()));
    
    // Render the image in an 'img' element.
    const imgElement = document.createElement('img');
    imgElement.src = myImage.toURL();

    This is the returned URL:

To let Cloudinary select the optimal format for each browser, use the delivery action, setting format to auto. For example, in Chrome, this image delivers in .webp format.

Copy to clipboard
import {Cloudinary} from "@cloudinary/base";
import {auto} from "@cloudinary/base/qualifiers/format";
import {format} from "@cloudinary/base/actions/delivery";

// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
}); 

// Use the image with public ID, 'sample'.
const myImage = cld.image('sample');

// Request automatic format.
myImage.delivery(format(auto()));

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

This is the returned URL:

For more details see Image format support.

Applying image effects and filters

You can select from a large selection of image effects, enhancements, and filters to apply to your images. The available effects include a variety of color balance and level effects, tinting, blurring, pixelating, sharpening, automatic improvement effects, artistic filters, image and text overlays, distortion and shape changing effects, outlines, backgrounds, shadows, and more.

For example, the code below applies a cartoonify effect, rounding corners effect, and background color effect (and then scales the image down to a height of 300 pixels).

Copy to clipboard
import {Cloudinary} from "@cloudinary/base";
import {scale} from "@cloudinary/base/actions/resize";
import {outline, cartoonify} from "@cloudinary/base/actions/effect";
import {max} from "@cloudinary/base/actions/roundCorners";
import {outer} from "@cloudinary/base/qualifiers/outlineMode";
import {Color} from "@cloudinary/base/qualifiers/color";

// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
}); 

// Use the image with public ID, 'actor'.
const myImage = cld.image('actor');

// Apply the transformation.
myImage
  .effect(cartoonify())
  .roundCorners(max())
  .effect(outline().mode(outer()).width(100).color(Color.LIGHTBLUE))
  .backgroundColor(Color.LIGHTBLUE)
  .resize(scale().height(300));

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

An image with several transformation effects

For more details on the available image effects and filters, see Visual image effects and enhancements.

Adding text and image overlays

You can add images and text as overlays on your main image. You can apply the same types of transformations on your overlay images as you can with any image and you can use gravity settings or x and y coordinates to control the location of the overlays. You can also apply a variety of transformations on text, such as color, font, size, rotation, and more.

For example, the code below overlays a couple's photo on a mug image. The overlay photo is cropped using face detection with adjusted color saturation and a vignette effect applied. The word love is added in a pink, fancy font and rotated to fit the design. A balloon graphic is also added. Additionally, the final image is cropped and the corners are rounded.

Tip
Although at first glance this example may look complicated, take the time to look through the code and you'll see it's actually quite intuitive!

Copy to clipboard
import {Cloudinary} from "@cloudinary/base";
import {Transformation} from "@cloudinary/base";
import {scale, fill, crop} from "@cloudinary/base/actions/resize";
import {source} from "@cloudinary/base/actions/overlay";
import {byAngle} from "@cloudinary/base/actions/rotate"
import {vignette} from "@cloudinary/base/actions/effect";
import {byRadius, max} from "@cloudinary/base/actions/roundCorners";
import {saturation, hue} from "@cloudinary/base/actions/adjust";
import {Position} from "@cloudinary/base/qualifiers/position";
import {faces} from "@cloudinary/base/qualifiers/focusOn";
import {compass} from "@cloudinary/base/qualifiers/gravity";
import {focusOn} from "@cloudinary/base/qualifiers/gravity";
import {image, text} from "@cloudinary/base/qualifiers/source";
import {south, center} from "@cloudinary/base/qualifiers/compass";
import {TextStyle} from "@cloudinary/base/qualifiers/textStyle";
import {bold} from "@cloudinary/base/qualifiers/fontWeight";

// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
});

// Use the image with public ID, 'coffee_cup'.
const myImage = cld.image('coffee_cup');

// Apply the transformation.
myImage
  .resize(fill().height(250).width(400).gravity(compass(south())))
  .overlay(
    source(
      image('nice_couple')
          .transformation(new Transformation()
          .resize(crop().width(1.3).height(1.3).gravity(focusOn(faces())).regionRelative())
          .adjust(saturation(50))
          .effect(vignette())
          .resize(scale().width(100))
          .roundCorners(max())
          )
      )
      .position(new Position().gravity(compass(center())).offsetX(-20).offsetY(20)) 
  )
  .overlay(
    source(
      image('balloon')
        .transformation(new Transformation()
        .resize(scale().height(55))
        .adjust(hue(-20))
        .rotate(byAngle(5))
        )
    )
    .position(new Position().gravity(compass(center())).offsetX(30).offsetY(5)) 
  )
  .overlay(
    source(
      text('Love', new TextStyle('Cookie',40)
        .fontWeight(bold()))
        .textColor('#f08')
        .transformation(new Transformation()
        .rotate(byAngle(20)))
    )
    .position(new Position().gravity(compass(center())).offsetX(-45).offsetY(44)) 
  )
  .resize(crop().width(300).height(250).x(30))
  .roundCorners(byRadius(60));

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

An image with many transformations and overlays applied

Image optimizations

By default, Cloudinary automatically performs certain optimizations on all transformed images. There are also a number of additional features that enable you to further optimize the images you use in your JavaScript application. These include optimizations to image quality, format, and size, among others.

For example, you can use the auto qualifier for the fetch-format and quality attributes to automatically deliver the image in the format and quality that minimize file size while meeting the required quality level. Below, these two parameters are applied, resulting in a 50% file size reduction (1.4 MB vs. 784 KB) with no visible change in quality.

Copy to clipboard
import {Cloudinary} from "@cloudinary/base";
import {format, quality} from "@cloudinary/base/actions/delivery";
import {auto} from "@cloudinary/base/qualifiers/format";
import {auto as qAuto} from "@cloudinary/base/qualifiers/quality";

// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
}); 

// Use the image with public ID, 'pond_reflect'.
const myImage = cld.image('pond_reflect');

// Request automatic format and quality.
myImage
  .delivery(format(auto()))
  .delivery(quality(qAuto()));

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

50% file size optimization using auto format and auto quality features

For an in-depth review of the many ways you can optimize your images, see Image optimization.

✔️ Feedback sent!

Rate this page: