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

Copy to clipboard
// Upload image to cloud
cloudinary.v2.uploader.upload('lady.jpg',
    function(error, result) {console.log(result); }
);
Copy to clipboard
// 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:

on demand

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:

Copy to clipboard
// 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:

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

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

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:

Copy to clipboard
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:

Copy to clipboard
// 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

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