Cloudinary Blog

Painless image and video manipulation with JavaScript

Painless image and video manipulation with JavaScript

TL;DR

Cloudinary’s JavaScript library accelerates web development by providing automated image manipulation 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 manipulate 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 image manipulation 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:

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

Scaled down elephants image to 500 pixels

You can also generate the entire image tag:

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:

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

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.

For further information on each class, see the API reference.

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

Here are a few examples:

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 manipulation, 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:

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

New version:

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

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

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

Each package has it's own API documentation site:

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 manipulation 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

How to Make Boomerang Video Effect With Cloudinary

When you see the term boomerang, what is the first thing that comes to mind?

A thrown tool made of wood that returns to its thrower? Another definition is reversal, logically portraying the aim of the tool itself. Based on this definition, the term boomerang videos” came into play to depict videos that loop back and forth.

Read more
Shortening the Development Cycle of Media-Related apps with Cloudinary

Currently, the Android platform boasts the highest demand for mobile solutions, as evidenced by Google’s announcement in 2017 that there were two billion monthly active Android devices, a number that is likely to increase in the years ahead. For app developers like you, now is the right time to build and release solutions for Android. you might have also noticed that a higher percentage of apps being developed nowadays are filled with visual media: images and videos.

Read more
Build Your Own Image Storyboard Android App

Globally, approximately two billion people now own smartphones, which also feature cameras capable of capturing photos and videos of a tonal richness and quality unimaginable even five years ago. Until recently, those cameras behaved mostly as optical sensors, catching light that determines the resulting image's pixels. The next generation of cameras, however, can blend hardware and computer-vision algorithms that apply to an image's semantic content, spawning creative mobile photo and video apps.

Read more
Cloudinary Delivers Simplified Image Management Workflow for Fairfax Media's Digital Transformation

Fairfax Media Limited [ASX:FXJ] is one of the largest media companies in Australia and New Zealand that engages audiences and communities via print and digital media. It includes recognizable mastheads including The Australian Financial Review, The Sydney Morning Herald and The Age. Fairfax Media operates numerous news and information websites, as well as tablet and smartphone apps, for online news sites.

Read more
Bleacher Report Scores with Real-Time Video Highlights Delivered by Cloudinary

Bleacher Report is a global digital destination for sports fans, creating and collaborating on content at the intersection of sports and culture. Owned by Turner, a division of Time Warner, Bleacher Report's website and social channels focus on sports culture for the next generation of fans. Bleacher Report also has a five-star mobile app and popular email newsletters, which are part of the company’s strategy for instantly delivering in-depth articles, results and video highlights personalized for users’ favorite teams, players and leagues.

Read more