Cloudinary Blog

Automated JavaScript Image Transformation and Management

By Amir Tocker
Automated JavaScript Image Transformation and Management

TL;DR

Cloudinary’s JavaScript library accelerates web development by providing automated JavaScript image transformation and management with a few lines of code. The newly released version streamlines the library by providing a much requested jQuery-free core library. At the same time it is fully backward compatible with previous versions. The new library is further enhanced with classes and a chainable API, making the implementation of Cloudinary functionality in your application easier (and more enjoyable!).

Overview

Virtually all websites incorporate images and videos in their web pages. With the proliferation of web platforms, devices and rising user expectations, handling media is an increasingly complex task. Services such as Cloudinary alleviate the pain by relieving the developer from having to manually transform images, respond to device and layout constraints, and manage storage and availability concerns.

A typical mistake made by novice developers is to provide full size images on the web page. This guaranties that the page will look great on the highest resolution, but at a large cost to download and response times - not to mention bandwidth costs.

The easiest solution - using JavaScript image transformation software to create a smaller resolution version of each image - is quickly revealed to be an exponentially difficult task. For one thing, you have to code your web page to display the right image file. Furthermore, you have to keep track of all files related to the same source image. And any change in layout may require rescaling and re-cropping.

Rinse and repeat for each and every image.

Cloudinary’s JavaScript library essentially eliminates this nightmare.

Cloudinary’s strength is largely due to its ability to transform images using a simply coded URL. For example, adding c_scale,w_500 to the URL will scale the image to a width of - you guessed it - 500 pixels. The image is automatically scaled and cached on a CDN, ready to be served.

Cloudinary’s JavaScript API  provides the functionality required to programmatically declare the required transformations and generate Cloudinary resource URLs. For example, the aforementioned transformation can be expressed using the following configuration object: {crop: “scale”, width: 500}.

Creating the imageURL (which will also generate a new image) is simple and intuitive:

Copy to clipboard
cl.url( "elephants.jpg", {crop: "scale", width: 500});

Scaled down elephants image to 500 pixels

You can also generate the entire image tag:

Copy to clipboard
cl.image( "elephants.jpg", {crop: "scale", width: 500});
// <img src="https://res.cloudinary.com/demo/image/upload/c_scale,w_500/elephants.jpg" width="500">

For more artistic results:

Copy to clipboard
var artistic = Transformation.new()
       .crop("scale")
       .width(500)
       .radius("max")
       .effect("oil_paint:50");

cl.image("elephants.jpg", artistic);
// <img src="https://res.cloudinary.com/demo/image/upload/c_scale,e_oil_paint:50,r_max,w_500/elephants.jpg" >

Oil paint image effect

Copy to clipboard
cl.image("horses.jpg", artistic);
// <img src="https://res.cloudinary.com/demo/image/upload/c_scale,e_oil_paint:50,r_max,w_500/horses.jpg" >

Oil paint effect of the horses photo

See what I mean?

In addition, the SDK provides the functionality required to upload images from the browser directly to the cloud, and apply responsive behavior to the displayed images. For more information on the available SDKs and media transformation options, see Cloudinary’s documentation.

Main Features

The Cloudinary JavaScript library functionality is represented using several classes.

The main class, Cloudinary, provides an API for:

  • Generating resource URLs.
  • Generating HTML.
  • Generating transformation strings.
  • Enabling responsive behavior.

In addition, other classes encapsulate specific behavior:

  • Transformation - generates and represents transformations.
  • Configuration - manages the Cloudinary API configuration.
  • HtmlTag, ImageTag, VideoTag - generates HTML tags.
  • Util - various utility functions.

After providing basic configuration values, the API is ready to be used.

Here are a few examples:

Copy to clipboard
var cl = cloudinary.Cloudinary.new( { cloud_name: "demo"});

var d = document.getElementById("my_div");

d.appendChild( cl.imageTag("sample", {crop: "scale", width: 200}).toDOM());

var i = document.getElementById(my_image);

i.src = cl.url( "sample", {crop: "scale", width: 200, angle: 30});

Rejuvenating a library

When we first wrote our JavaScript library, it was designed as a jQuery plugin. Virtually all JavaScript developers are familiar with jQuery: it is one of the most popular JavaScript libraries and has a large following. It is designed by and large for client side HTML/DOM transformation, but includes many useful general purpose functions. jQuery takes the hassle away from many of the woes of web development and has served developers well. The jQuery library also provides browser compatibility by handling special cases and ensuring that the JavaScript code will run on virtually all clients.

However with the recent rise in the number of JavaScript libraries, frameworks and, well, tastes, we have also received many requests to create a jQuery-less library.

The decisions facing one in the task of redesigning a JavaScript library are numerous and daunting. Backward compatibility vs. a clean break? native JavaScript vs. CoffeeScript / TypeScript? lodash, underscore, or implement your own solutions? Npm, Bower or both? Grunt, Gulp, npm? RequireJS, CommonJS, webpack, browserify? - well, you get the point.

Javascript framework and tools

Too many choices

Needless to say each choice you make will provoke praise from one camp and battle cries from the other…

Backward Compatibility

Backward compatibility is obviously a big issue. Our philosophy is to let our customers enjoy new features with minimal code changes - if any. The nature of our service also requires that our libraries support a wider range of platforms and browser versions than normally needed. To this end, the new library was designed to be a drop-in replacement to the existing library. This decision has put some constraints on the design of the library - but we were happy (and proud) to have accomplished it in full.

Old version:

Copy to clipboard
$.cloudinary.url(my_image, {width: 100});

New version:

Copy to clipboard
$.cloudinary.url(my_image, {width: 100});

Backward compatibility, anyone? the new library is a drop-in replacement.

The cloudinary_js library is provided in plain javascript 5. This is important to ensure it will run smoothly regardless of the browser the end user is using. During the development phase, it is often easier to code in a higher function variation of the language.

Early on we made the decision to write the new code in CoffeeScript. While ES2015 (the artist formally known as ES6) was already rolling out, maintaining backward compatibility meant that we would have to “compile” the code anyway. CoffeeScript has its own shortcomings but its familiarity to Rails developers, and the fact the our NodeJS library was written in CoffeeScript, made it a comfortable choice. Besides, comprehensions are cool!

CoffeeScript and ES2015 both allow the creation of classes and objects. Syntax may vary (as does the implementation of class inheritance) but the result is similar. In fact both are mainly syntactic-sugar to a functionality that already existed in “native” JavaScript.

The new library groups functionality into classes. One of the neat benefits is the ability to chain function calls, making the code more descriptive.

The following code, for example, configures the Cloudinary API to use the cloud “demo”.

It then creates an image tag for the “sample” image, scaled to a width of 150px, rotated by 15 degrees, and with the “sepia" effect applied.

Copy to clipboard
var cl = cloudinary.Cloudinary.new({cloud_name: "demo"});
var tag = cl.imageTag("sample").transformation()
   .width(150)
   .crop("scale")
   .angle(15)
   .effect('sepia');

Since the code is object oriented (rather than global as in the previous version), it is easy to utilize multiple clouds and accounts in the same application.

The following code creates two image tags drawn from two different clouds (note that while the public ID of the image is the same these could be two completely different images as they are defined in separate clouds).

Copy to clipboard
var someCloud = cloudinary.Cloudinary.new( {cloud_name: "someCloud", secure: true});
var otherCloud = cloudinary.Cloudinary.new( {cloud_name: "otherCloud"});

someCloud.imageTag("sample.jpg"); // <img src="https://res.cloudinary.com/someCloud/image/upload/sample.jpg">
otherCloud.imageTag("sample.jpg"); // <img src="https://res.cloudinary.com/otherCloud/image/upload/sample.jpg">

Utility functions

The JavaScript language has limitations, be it array transformation or determining an “empty” value. Some of these limitations were addressed in ES2015, but as a JavaScript developer you always have to be on your toes making sure that the feature you are using will be supported in all foreseeable environments.

Libraries such as lodash take the edge off by providing an implementation of features when the runtime environment does not support them. Because jQuery support was still required for the Cloudinary jQuery plugin, and because we anticipated frowns on the use of lodash, we designed the library so that lodash is not called directly but through the “util” interface. This allows us to switch between jQuery and lodash when needed. It also allows for the future utilization of a different library, or for a keen programmer to implement “native” code and make the library become fully standalone.

We also created a special shrinkwrapped version of the library which includes a subset of the lodash functions that are required by Cloudinary. The resulting single file is about half the size of a full sourced lodash + Cloudinary.

Uploading a file using JavaScript is basically not a difficult task, but it gets complex quickly and deeply so. To avoid this we have relied in the past on Blueimp’s excellent jQuery-file-upload library. For both backward compatibility and the fact that this library does what it does well, we decided to keep using it. As much as this library is useful however, you can still utilize other upload libraries or write your own code to upload files from the core library. See this example of a pure JavaScript upload to Cloudinary.

New source repositories

There are two common ways to manage dependent libraries in JavaScript: npm and bower. Originally, bower handled client side libraries while npm, as its name suggests (Node Package Manager) was managing server side libraries. Today npm is used to manage client side libraries too. In fact jQuery, which used to have its own repository, moved its plugins to npm.

In order to serve both the core library and the jQuery variant we had to create 3 new github repositories. The main reason was that bower relies directly on the github release information, which means you cannot serve two packages from the same repository.

The main repository which includes the source code, issues and pull requests for the Cloudinary JavaScript library is located at cloudinary_js. In order to support existing websites that relied on the previous version of this library, it includes a backward compatible distribution format.

The new JavaScript API is provided in 3 distribution packages:

Github Repository

Package name

Description

pkg-cloudinary-core

cloudinary-core

Core Cloudinary Library.

Use this if you do not intend to use jQuery.

pkg-cloudinary-jquery

cloudinary-jquery

Core Library + jQuery plugin

pkg-cloudinary-jquery-file-upload

cloudinary-jquery-file-upload

Core Library + jQuery plugin

+ Blueimp File Upload adapter

The same package names are used in both bower and NPM.

This API reference is generated directly from the code and complements the documentation on our main website.

Summary

The management of images and other media resources is an important part of modern web and mobile development. The Cloudinary JavaScript library significantly reduces the workload by automating the transformation and delivery of the resources.

The new version of the library includes 3 distributions: the core library, the jQuery plugin, and the File Upload plugin.

The library also introduces a new API that allows the developer to chain function calls and use multiple accounts in the same application.

Head over and give it a try at cloudinary_js!

We’re looking forward to hearing your impressions!

Elephants image is under CC0 license. The source of the image is here.

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