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:

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 behaviour 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:

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

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

Generate Waveform Images from Audio with Cloudinary

This is a reposting of an article written by David Walsh. Check out his blog HERE!
I've been working a lot with visualizations lately, which is a far cry from your normal webpage element interaction coding; you need advanced geometry knowledge, render and performance knowledge, and much more. It's been a great learning experience but it can be challenging and isn't always an interest of all web developers. That's why we use apps and services specializing in complex tasks like Cloudinary: we need it done quickly and by a tool written by an expert.

Read more
Make All Images on Your Website Responsive in 3 Easy Steps

Images are crucial to website performance, but most still don't implement responsive images. It’s not just about fitting an image on the screen, but also making the the image size relatively rational to the device. The srcset and sizes options, which are your best hit are hard to implement. Cloudinary provides an easier way, which we will discuss in this article.

Read more

The Future of Audio and Video on the Web

By Prosper Otemuyiwa
The Future of Audio and Video on the Web

Web sites and platforms are becoming increasingly media-rich. Today, approximately 62 percent of internet traffic is made up of images, with audio and video constituting a growing percentage of the bytes.

Read more

Embed Images in Email Campaigns at Scale

By Sourav Kundu
Embed Images in Email Campaigns at Scale

tl;dr

Cloudinary is a powerful image hosting solution for email marketing campaigns of any size. With features such as advanced image optimization and on-the-fly image transformation, backed by a global CDN, Cloudinary provides the base for a seamless user experience in your email campaigns leading to increased conversion and performance.

Read more
Build the Back-End For Your Own Instagram-style App with Cloudinary

Github Repo

Managing media files (processing, storage and manipulation) is one of the biggest challenges we encounter as practical developers. These challenges include:

A great service called Cloudinary can help us overcome many of these challenges. Together with Cloudinary, let's work on solutions to these challenges and hopefully have a simpler mental model towards media management.

Read more

Build A Miniflix in 10 Minutes

By Prosper Otemuyiwa
Build A Miniflix in 10 Minutes

Developers are constantly faced with challenges of building complex products every single day. And there are constraints on the time needed to build out the features of these products.

Engineering and Product managers want to beat deadlines for projects daily. CEOs want to roll out new products as fast as possible. Entrepreneurs need their MVPs like yesterday. With this in mind, what should developers do?

Read more