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

Find images & videos with a robust new search engine

Great content is hard to come by. You can invest a lot of time and effort in building a great media library, but if content managers and editors can't quickly find what they need at the right time, it's almost useless (and frustrating). Good search capabilities allow you to provide them with a better experience: present relevant content or a well-organized catalog by a variety of criteria such as tags, folders, size, resolution, aspect ratio, faces, colors and many more.

Read more
Video at Large Scale - Contributions from the Developer Community

Video is an increasingly important component for websites - whether it’s to inform visitors, enhance user experience or support sales and marketing efforts. But delivering high-quality video at large scale can be quite a challenge. You need to consider encoding, format, bandwidth usage, delivery and the devices on which visitors may be watching the video, to name just a few concerns.

Read more

Image Optimization in WordPress

By Prosper Otemuyiwa
Image Optimization in WordPress

WordPress is the number one content management system (CMS) in use today, running approximately 27 percent of the entire internet. Several high-traffic websites run on WordPress, and many utilize media, such as images and videos, to attract users and meet their needs.

 

Read more

Build a Vue Watermarking App for your Image Gallery

By Christian Nwamba
Build a Vue Watermarking App for your Image Gallery

If you intend to build a photo gallery online, you have to seriously consider how to protect the images from users who are not buying them. While visitors need to see the picture before purchasing, there needs to be a way to ensure that even serious buyers are not tempted to use the images without agreeing to your license terms.

Read more
Introducing Website Speed Test: An Image Analysis Tool Integrated with WebPagetest

Because images dominate page weight, methodical image optimization can have a significant effect on conversions and user experience. And the performance tools you choose to use can have a powerful impact on how websites are built and maintained. One such popular open source tool is WebPagetest. It is designed to measure and analyze webpage performance, which is why Cloudinary chose to partner with our friends over there to launch Website Speed Test.

Read more

You might have read some tutorials or articles explaining the importance of images and how to optimize them to deliver a great experience to your users. But does this work really translate into wins for your company? In this talk, you see real-world examples of the positive impact that image optimizations can have on metrics that your bosses and clients care about. You will walk away from this talk with compelling data and useful tools to help you get buy-in and support for this important user experience work at your company.

Read more