Generate Responsive Images for Reduced Bandwidth

reduced bandwith

Visitors to your website expect an optimized user experience. One key aspect of this is faster page loads. An easy way to achieve faster load times is reducing your image size and overall bandwidth.

When you automatically generate responsive images you save bandwidth as the responsive images are naturally scaled to suit a user’s screen. Unfortunately, when making images responsive, a user rarely gets served an image in the size that best fits their screen. Instead, the image is sized to the nearest width.

This article explains how to automatically generate responsive images that are the exact dimensions for the viewing device rather than generate images to the nearest of 3 or 4 fixed dimensions.

Generating responsive images

The common process for generating responsive images is:

  1. Resize an image into at least three sizes.
  2. Export the sizes in the formats you want (WebP/JPEG/PNG).
  3. Optimize them for web delivery.
  4. Write the code to detect and serve the right image.

 

Example:

    <img 
      sizes="(max-width: 320px) 280px, (max-width: 480px) 440px, 800px"
      srcset="dog-320.jpg 320w, dog-480.jpg 480w, dog-800.jpg 800w" 
      src="dog-800.jpg"
    />

However, Cloudinary, an end-to-end media management solution for websites and applications, automatically generates responsive images through a variety of ways:

The cloudinary-core JS library is used in this article.

Using the cloudinary-core JS library

Using the cloudinary-core JS library, you can create the correct DPR (Device Pixel Ratio) image for devices that support higher resolutions and automate the width. The JS code checks the device’s DPR and the space available for the image. Users of high pixel-density devices will get a great result but may have to wait longer for images to load, while low DPR users won’t have to wait for large images to load.

Prerequisites

Step 1: Upload an image to Cloudinary

To upload an image to Cloudinary, create an account for free. After creating an account and logging in, click Media Library near the top left corner of the dashboard:

 

Welcome

Once in the Media Library, select the blue Upload button:

Media Library Upload Button

To follow along with this tutorial, paste the image URL found in the prerequisites in the upload window:

Public URL file to upload

 

After the image uploads to your Media Library, copy its URL as shown below:

New Image Happy

 

The URL will be similar to:

https://res.cloudinary.com/dodazie/image/upload/happy.jpg

To break down the above URL:

      • res.cloudinary.com/ is Cloudinary’s base URL.
      • dodazie is a Cloudinary account’s cloud name.
      • image/upload/ is the path to the images uploaded to your media library.
      • happy is the name of the image.
      • .jpg is the format of this image. You can also request a .png or .WebP format by easily swapping out the .jpg for the format of your choice. Even though the original uploaded image is .jpg. Cloudinary will convert the format on the fly.
        Next, we will use the cloudinary-core JS library to automate the responsiveness of the above image.

        Step 2: Integrate the cloudinary-core JS library

        To integrate the cloudinary-core JS library, you can use a package manager (yarn, npm) or include the library in your HTML pages.

        Using a package manager

            npm install cloudinary-core
        

        Or

            yarn install cloudinary-core
        

        To include the library in your HTML pages

            <script
              src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.js"
              type="text/javascript">
            </script>
        

         

        The above cloudinary-core-shrinkwrap.js library is a shrink-wrapped version of the cloudinary-core library (it is not dependent on lodash).

        This article will use the library on an HTML page.

        Step 3: Set your HTML <img> tags parameters

        For each image you want to make responsive:

        1. Stick the data-src attribute of the <img> tag to the URL of the image you uploaded to Cloudinary. You don’t need to set the src attribute of the <img> tag as it is updated dynamically.
        2. Using Cloudinary image transformation URL parameters, set the crop parameter to scale and the width and dpr parameters to auto — c_scale,w_auto/dpr_auto in the URL between upload/ and the image name:

https://res.cloudinary.com/dodazie/image/upload/c_scale,w_auto/dpr_auto/happy.jpg

      1. This will allow Cloudinary to automatically generate responsive images scaled to the accurate width value based on the DPR of the device and the identified width available for the images in the containing element.
      2. Add the cld-responsive class to the <img> tag. cld-responsive is the default class name, however, you can create custom class names and programmatically make HTML elements responsive.Your <img> tag will be:
            <img 
                data-src="https://res.cloudinary.com/dodazie/image/upload/c_scale,w_auto/dpr_auto/happy.jpg" 
                class="cld-responsive"
            >
        

        Step 4: Call the Cloudinary responsive() method

At the end of the HTML page, add a call to Cloudinary’s responsive() JavaScript method:

    <script type="text/javascript">
        var cloudinary = cloudinary.Cloudinary.new({cloud_name: "<YOUR_CLOUD_NAME>"}); 
        cloudinary.responsive();
    </script>

The above responsive() method looks for all images on the page with the cld-responsive class name, detects the available width for the image on the page, and updates the HTML <img> tags accordingly. The image will also update whenever the window size or screen resolution changes.

 

Resolution changes responsive images

 

Conclusion

Now you are ready to automate the responsiveness of the images on your website and provide visitors to your website an optimized user experience!

The process presented in this article covers the simplest way to automatically generate responsive images that are the exact dimensions for the viewing device. You can further customize the behavior to control whether to update images on resizing, when to update the image using stop-points, preserve the CSS image height, etc. To learn more, view the Cloudinary documentation.

Ready to get started? Create an account for free.

More from Cloudinary

 

QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you effectively generate responsive images for reduced bandwidth:

  1. Use Cloudinary’s w_auto and dpr_auto for precise scaling
    When defining Cloudinary URLs, utilize w_auto (width auto) and dpr_auto (device pixel ratio auto) parameters to automatically generate responsive images based on the viewport and device pixel density. This setup ensures that users on high-DPI screens get sharper images, while lower-resolution screens receive smaller, optimized versions.
  2. Set specific sizes attributes based on actual layout widths
    Use the sizes attribute to define image widths at different breakpoints, ensuring the browser picks the best size based on your design. Avoid generic values like 100vw (100% viewport width) for all images, as this may lead to over-serving large images unnecessarily. Instead, specify context-based sizes, like 50vw for half-width columns.
  3. Implement client hints for dynamic image optimization
    Utilize HTTP Client Hints (DPR, Viewport-Width, and Width) to dynamically serve the best image variant based on the client’s screen attributes. Configure your server or use a platform like Cloudinary to read these hints and automatically serve appropriately sized images.
  4. Utilize q_auto for smart quality adjustment
    When generating responsive images, always add q_auto (quality auto) to Cloudinary URLs to automatically adjust the quality based on the image content and the visual impact. This optimization method ensures a balance between quality and file size, avoiding unnecessary large file downloads.
  5. Create dynamic breakpoints instead of fixed dimensions
    Rather than manually defining a few fixed image sizes (e.g., small, medium, large), use dynamic breakpoints based on content analysis or device characteristics. Cloudinary’s responsive breakpoint generator can help automate this process, reducing the guesswork and ensuring precise fit for all devices.
  6. Incorporate lazy loading to avoid loading off-screen images
    Implement lazy loading for images using the loading="lazy" attribute or IntersectionObserver to delay loading of off-screen images until they’re about to appear in the viewport. This drastically reduces the initial page load time, improving performance for users on slower networks.
  7. Use progressive image formats for perceived speed
    Serve images in progressive formats (e.g., progressive JPEG or WebP) that load in multiple passes, showing a low-quality version first. This technique improves the perceived speed of loading, giving users visual feedback even before the full image is downloaded.
  8. Test different format options using f_auto
    Use the f_auto (format auto) parameter in Cloudinary to dynamically choose the most efficient image format for each browser. This feature allows you to serve WebP, AVIF, or JPEG depending on which format the browser supports, achieving optimal performance with minimal file sizes.
  9. Incorporate Cloudinary’s responsive method for automatic updates
    When using the Cloudinary JS library, call the responsive() method after setting your data-src attributes. This ensures that images are automatically resized whenever the screen is resized or the device changes orientation, maintaining the best fit for the available space.
  10. Audit image performance with Core Web Vitals
    Regularly analyze your image performance using tools like Google Lighthouse and WebPageTest to assess metrics like Largest Contentful Paint (LCP) and Cumulative Layout Shift (CLS). Optimize based on these metrics to ensure your responsive images deliver a fast, stable, and visually satisfying experience across all devices.

Implementing these techniques will help you automatically generate and deliver responsive images that save bandwidth, reduce page load times, and provide an optimal visual experience across various screen sizes and resolutions.

Last updated: Oct 1, 2024