Cloudinary Blog

Should You Transform Images On Upload or On Demand?

By Christian Nwamba
Should You Transform Images On Upload or On Demand?

As a developer, you hope and anticipate that your website or mobile application will be accessed by different users on various devices. To improve the user-experience, irrespective of the viewing device, you need to make sure that each image adapts to different graphic layouts, device resolutions and other viewing requirements. For example, for an E-Commerce site, one image will be displayed on different pages — home page, product page, shopping cart and more — and will be viewed on a desktop, cellphone or a tablet. This means that you need to create numerous versions of every image and for a website with hundreds of images, manual manipulation is not scalable.

Cloudinary enables you to programmatically transform original images from various sources based on viewing requirements.

Lazy and Eager Transformation

Cloudinary offers multiple strategies for transforming your images. In this article, we’ll discuss two options: “lazy transformations”, which is the default option, and “eager transformations”, which can be selected by adding a flag to the upload API call.

Lazy transformation entails uploading images to Cloudinary as is and then transforming the images only when a user requests the image. The transformation for a given user is performed once, cached and delivered via a CDN for subsequent requests.

This type of transformation is the default option because it limits the bandwidth usage by generating transformations on-demand.

Let’s look at an example:

// Upload image to cloud
cloudinary.v2.uploader.upload('lady.jpg',
    function(error, result) {console.log(result); }
);
// Request image and lazy-transform the image
cloudinary.url("lady.jpg", 
    // Transformation
    {transformation: [
  {width: 400, height: 400, gravity: "face", radius: "max", crop: "crop"}
  ]})

The uploaded image is transformed only when requested with cloudinary.url, which returns a transformed image URL. This is what the request looks like in the network tab:

Even as small as the transformed image is (4.2kb), it still took as much as 976ms to complete the request. Consider how much time it would take if we had up to 50 images that required such transformations on one page of our website. Additionally, customers attempting to access these images during this 1 second in which they are created, will get broken images (error 420) due to concurrent access.

There are cases where, due to highly concurrent access patterns, it is not a good idea to wait until the first access to create the derived image or video. For example, if you run a news site, and tweet about your new article, for thousands of users to access it concurrently, and the images and videos on the article page were not created in advance, many of these users could encounter concurrency issues. In this case, the first user will experience a delay in accessing the images and videos, and while these transformations are being created, rest of the users will get broken images and videos. Reloading the page would fix the problem, but you might lose some users by then.

One way to solve this is to have editors preview their pages before publishing. However, with responsive design, real-time communications, and multiple devices accessing the content, it’s best to make sure the images are created during upload.

Now let’s consider a better solution: Eager transformation.

Eager Transformation

Just as the name states, eager entails transforming images during upload so when the transformations are requested, they will always be optimized and delivered with the best possible performance. So, when a user requests an image, Cloudinary no longer needs to perform transformations on this image because it has already been completed during upload.

With the eager approach, transformation tasks are performed once (during upload) for all requests so users don’t experience any delays.

To perform an eager transformation, use the eager array, which accepts transformation configuration objects:

// Perform transformation while uploading
cloudinary.v2.uploader.upload("lady.jpg", 
    // Eager transformation
    { eager: [
        { width: 400, height: 300, crop: "pad" }, 
        { width: 260, height: 200, crop: "crop", gravity: "north"} ]}, 
    function(error, result) {console.log(result); });

You can pass as many transformation objects as you choose to the eager array. The callback will be executed once the upload and transformation is completed.

You can as well request the image, but this time, you don't transform:

// Request image without transforming the image
cloudinary.url("lady.jpg");

This is what the request looks like in the network tab:

Let’s consider an image larger in size (22.8k) compared to image in the lazy transformation example. The image request was completed at 469ms, which is about 50 percent faster than the lazy method.

Transforming with API URL

Cloudinary provides a SDK for most of the platforms available today, including .Net, Node, PHP, Ruby, Python, React and Angular. If you want to talk directly to the API, that is possible. For eager transformation, you can use the eager parameter to carry out your actions:

eager=c_crop,w_400,h_400,g_face/w_50,h_50,c_scale|w_30,h_40,c_crop,g_south

The eager parameter receives a list of transformation strings separated with a pipe character (|). Chained transformations are separated with a slash (/).

What Of My Existing Images?

You no doubt have other images already stored on your cloud. It’s possible to use eager transformation on those as well.

Cloudinary allows you to perform explicit transformations on your existing images using the explicit method:

// Update existing image
cloudinary.v2.uploader.explicit('lady', 
      { eager: [
          { width: 200, crop: "scale" }, 
          { width: 360, height: 200, crop: "crop", gravity: "north"} ] }, 
    function(error, result) {console.log(result); } );

The method takes the name of the existing image as the first argument, then options (which transformation is part of) as the second argument and then the callback function to handle the completed update.

Conclusion

Eager transformation delivers better performance, and an improved user experience, while consuming fewer resources. Transformation is just one of the many features you can get from Cloudinary. Learn more.

This post originally appeared on Scotch.io

Christian Nwamba Christian Nwamba (CodeBeast), is a JavaScript Preacher, Community Builder and Developer Evangelist. In his next life, Chris hopes to remain a computer programmer.

Recent Blog Posts

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

Your Web Image is Unnecessarily Bloated

By Christian Nwamba
Your Web Image is Unnecessarily Bloated

As a developer, it seems inefficient to serve a 2000kb JPEG image when we could compress images to optimize the performance without degrading the visual quality.

We are not new to this kind of responsibility. But our productivity will end up being questioned if we do not deliver fast. In order to do so, the community has devised several patterns to help improve productivity. Let's review few of these patterns based on their categories:

Read more

Google For Nigeria: We saw it all…

By Christian Nwamba
Google For Nigeria: We saw it all…

Note from Cloudinary: Christian Nwamba, a frequent Cloudinary contributor, recently attended, and was a main speaker, at the Google Developer Group (GDG) Conference in Lagos, Nigeria. Christian led a session teaching more than 500 developers how to “Build Offline Apps for the Next Billion Users.” The stack he used included JS (Vue), Firebase, Service Workers and Cloudinary. Below is his account of the conference and his talk.

Read more
Viral Images: Securing Images and Video uploads to your systems

When was the last time you got paid $40,000 for a few days of work? That is what happened last year to Russian independent security researcher Andrey Leonov, who discovered that if you upload a specially constructed image file to Facebook, you can make Facebook's internal servers, nested deep within their firewalls, run arbitrary commands to expose sensitive internal files in a way that could easily lead to a data breach.

Read more