Cloudinary Blog

How to Automatically Adapt Website Images to Retina and HiDPI Devices

Match Device Pixel Ratio by Automatically Adapting Images

Web development was much simpler only a few years ago, when we were building HTML pages that included images and photos, and all elements shared the same resolution units. If for example, you aimed at a standard 1024x768 screen, you knew these were exactly the number of pixels available for displaying HTML elements and images.

In 2010, Apple introduced the iPhone 4 with Retina display. In order to simplify things for developers, the logical screen resolution remained the same as previous iPhone models (640x960) while the physical screen resolution was exactly doubled (1280x1920). This means that if, for example, you embed an image tag in your HTML page with width of 200 pixels and height of 300 pixels, and you display a double-size image of 400x600 pixels, the Retina display shows all pixels of the larger image, resulting in a much clearer visual result and without performing browser-side down-scaling.


How to Optimize for Page Load Speed


Since then, most of Apple's devices support this Device Pixel Ratio (DPR) of 2.0 (double physical resolution compared to logical resolution), including iPhone, iPad and Macbook Pro laptops. Android smartphones and tablets followed this trend, but there is a large variety of Android devices with different Device Pixel Ratios. For example, Samsung Galaxy S III has a DPR of 2.0, while the Samsung Galaxy S4 and LG G2 have a DPR of 3.0 (triple physical resolution). Some Android devices have non-round DPR values as well: 1.3, 1.5 and even 0.75.

DPR Illustration

Your website or mobile site is probably accessed by many users with HiDPI devices, or laptops with DPR higher than 1.0, so you should deliver high-resolution images to match the high visual quality your users expect. However, [higher resolution images(https://cloudinary.com/blog/imageoptimizationforwebsitesbeautifulpagesthatloadquickly) weigh more bytes and take more time to deliver, so you should avoid delivering double resolution images to standard devices of DPR 1.0. If you want to deliver different image resolutions to each type of device, you first need to create multiple versions of an image for each supported DPR, then detect the DPR of the user's current device, and deliver the correct image version.

Creating and dynamically serving images with multiple resolutions, coupled with dynamic DPR detection for correct responsive delivery, can be quite challenging. That's why we introduced Cloudinary's Retina and HiDPI support with dynamic DPR detection and on-the-fly DPR-specific image delivery.

This new feature allows you to provide one image, and have it automatically adapted to the resolution appropriate to each user’s device or screen. Cloudinary will take your one image and automatically create versions of it, matching different resolutions, on the fly. Meaning that users of devices with high pixel density will get a great visual result, while low-DPR users don't have to wait needlessly for larger images to load.

Dynamic image scaling based on Device Pixel Ratio (DPR)

Let's take the following image named 'smiling_man' that was uploaded to Cloudinary's cloud-based image management service. The original image is of 849x565 pixels (below you can see a scaled down sample of 254x169 pixels)

Ruby:
Copy to clipboard
cl_image_tag("smiling_man.jpg")
PHP:
Copy to clipboard
cl_image_tag("smiling_man.jpg")
Python:
Copy to clipboard
CloudinaryImage("smiling_man.jpg").image()
Node.js:
Copy to clipboard
cloudinary.image("smiling_man.jpg")
Java:
Copy to clipboard
cloudinary.url().imageTag("smiling_man.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('smiling_man.jpg').toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("smiling_man.jpg")
React:
Copy to clipboard
<Image publicId="smiling_man.jpg" >

</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="smiling_man.jpg" >

</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="smiling_man.jpg" >

</cl-image>
.Net:
Copy to clipboard
cloudinary.Api.UrlImgUp.BuildImageTag("smiling_man.jpg")
Android:
Copy to clipboard
MediaManager.get().url().generate("smiling_man.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().generate("smiling_man.jpg")!, cloudinary: cloudinary)
Uploaded smiling man photo

Let's say that in your website or mobile application you need a 100x100 profile picture thumbnail of this uploaded photo. Cloudinary can perform this image manipulation on-the-fly. The following dynamic URL and sample code generates a 100x100 face-detection based version of the photo, by setting the width and height parameters to 100, selecting the fill crop mode with face gravity, for face-detection-based cropping:

Ruby:
Copy to clipboard
cl_image_tag("smiling_man.jpg", :width=>100, :height=>100, :gravity=>"face", :crop=>"fill")
PHP:
Copy to clipboard
cl_image_tag("smiling_man.jpg", array("width"=>100, "height"=>100, "gravity"=>"face", "crop"=>"fill"))
Python:
Copy to clipboard
CloudinaryImage("smiling_man.jpg").image(width=100, height=100, gravity="face", crop="fill")
Node.js:
Copy to clipboard
cloudinary.image("smiling_man.jpg", {width: 100, height: 100, gravity: "face", crop: "fill"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().width(100).height(100).gravity("face").crop("fill")).imageTag("smiling_man.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('smiling_man.jpg', {width: 100, height: 100, gravity: "face", crop: "fill"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("smiling_man.jpg", {width: 100, height: 100, gravity: "face", crop: "fill"})
React:
Copy to clipboard
<Image publicId="smiling_man.jpg" >
  <Transformation width="100" height="100" gravity="face" crop="fill" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="smiling_man.jpg" >
  <cld-transformation width="100" height="100" gravity="face" crop="fill" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="smiling_man.jpg" >
  <cl-transformation width="100" height="100" gravity="face" crop="fill">
  </cl-transformation>
</cl-image>
.Net:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Width(100).Height(100).Gravity("face").Crop("fill")).BuildImageTag("smiling_man.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().width(100).height(100).gravity("face").crop("fill")).generate("smiling_man.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setWidth(100).setHeight(100).setGravity("face").setCrop("fill")).generate("smiling_man.jpg")!, cloudinary: cloudinary)
100x100 face detection based thumbnail

Now, in order to generate the same photo, this time for a DPR of 2.0, all you need to do is to set the new dpr transformation parameter to 2.0. As you can see below, setting the dpr parameter to 1.0, 2.0 and 3.0 dynamically generates the same content with 100x100, 200x200 and 300x300 pixels respectively.

Ruby:
Copy to clipboard
cl_image_tag("smiling_man.jpg", :width=>100, :height=>100, :gravity=>"face", :dpr=>2.0, :crop=>"fill")
PHP:
Copy to clipboard
cl_image_tag("smiling_man.jpg", array("width"=>100, "height"=>100, "gravity"=>"face", "dpr"=>2.0, "crop"=>"fill"))
Python:
Copy to clipboard
CloudinaryImage("smiling_man.jpg").image(width=100, height=100, gravity="face", dpr=2.0, crop="fill")
Node.js:
Copy to clipboard
cloudinary.image("smiling_man.jpg", {width: 100, height: 100, gravity: "face", dpr: "2.0", crop: "fill"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().width(100).height(100).gravity("face").dpr(2.0).crop("fill")).imageTag("smiling_man.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('smiling_man.jpg', {width: 100, height: 100, gravity: "face", dpr: "2.0", crop: "fill"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("smiling_man.jpg", {width: 100, height: 100, gravity: "face", dpr: "2.0", crop: "fill"})
React:
Copy to clipboard
<Image publicId="smiling_man.jpg" >
  <Transformation width="100" height="100" gravity="face" dpr="2.0" crop="fill" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="smiling_man.jpg" >
  <cld-transformation width="100" height="100" gravity="face" dpr="2.0" crop="fill" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="smiling_man.jpg" >
  <cl-transformation width="100" height="100" gravity="face" dpr="2.0" crop="fill">
  </cl-transformation>
</cl-image>
.Net:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Width(100).Height(100).Gravity("face").Dpr(2.0).Crop("fill")).BuildImageTag("smiling_man.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().width(100).height(100).gravity("face").dpr(2.0).crop("fill")).generate("smiling_man.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setWidth(100).setHeight(100).setGravity("face").setDpr(2.0).setCrop("fill")).generate("smiling_man.jpg")!, cloudinary: cloudinary)

DPR 1.0 thumbnail

DPR 2.0 thumbnail

DPR 3.0 thumbnail

DPR 1.0                   DPR 2.0                                                     DPR 3.0

When embedding these images, in an HTML page for example, you should set the width and height image tag attributes to 100 for all three, although the actual image might have more pixels available, for an optimal visual result on HiDPI devices.

Copy to clipboard
<img width="100" height="100" src="https://res.cloudinary.com/demo/image/upload/c_fill,w_100,h_100,g_face,dpr_2.0/smiling_man.jpg"/>

You can create image tags that have the logical width and height (100x100 in our example), while the URL of the image can be a dynamic image manipulation URL that delivers a larger image according to the given dpr parameter. The three images below are all displayed within a 100x100 logical square, while you see more details and a better visual result for the last two images if you view this post using a HiDPI device.

DPR 1.0 thumbnail in HTML

DPR 2.0 thumbnail in HTML

DPR 3.0 thumbnail in HTML

DPR 1.0 (100x100, 4.6KB)                  DPR 2.0 (200x200, 12.1KB)                DPR 3.0 (300x300, 22.6KB)

Image overlays with dynamic Device Pixel Ratio (DPR) based resizing

Images delivered by web applications and mobile sites might be more complex and involve overlays. If you are already familiar with Cloudinary, you know that Cloudinary supports dynamically generating images with overlays and watermarks of other uploaded image (see this blog post for more details).

When adding overlays, you need the overlay image to be correctly resized according to the required pixel density of the device (along with the containing image). Setting the dpr transformation parameter applies the same resizing rules both to the containing image, and the included overlay.

For example, the following URL dynamically generates a 100x100 face-detection-based circular thumbnail of the same photo, and adds another image named cloudinary_icon as a semi-transparent watermark that fills 90% of the width of the containing image. Setting the dpr value to 1.0, 2.0 or 3.0 generates the following images, while resizing both the containing image and the overlay to match the required DPR.

Ruby:
Copy to clipboard
cl_image_tag("smiling_man.jpg", :transformation=>[
  {:width=>100, :height=>100, :gravity=>"face", :radius=>"max", :crop=>"thumb"},
  {:overlay=>"cloudinary_icon", :effect=>"brightness:200", :flags=>"relative", :width=>0.9, :opacity=>60},
  {:dpr=>2.0}
  ])
PHP:
Copy to clipboard
cl_image_tag("smiling_man.jpg", array("transformation"=>array(
  array("width"=>100, "height"=>100, "gravity"=>"face", "radius"=>"max", "crop"=>"thumb"),
  array("overlay"=>"cloudinary_icon", "effect"=>"brightness:200", "flags"=>"relative", "width"=>0.9, "opacity"=>60),
  array("dpr"=>2.0)
  )))
Python:
Copy to clipboard
CloudinaryImage("smiling_man.jpg").image(transformation=[
  {'width': 100, 'height': 100, 'gravity': "face", 'radius': "max", 'crop': "thumb"},
  {'overlay': "cloudinary_icon", 'effect': "brightness:200", 'flags': "relative", 'width': 0.9, 'opacity': 60},
  {'dpr': 2.0}
  ])
Node.js:
Copy to clipboard
cloudinary.image("smiling_man.jpg", {transformation: [
  {width: 100, height: 100, gravity: "face", radius: "max", crop: "thumb"},
  {overlay: "cloudinary_icon", effect: "brightness:200", flags: "relative", width: "0.9", opacity: 60},
  {dpr: "2.0"}
  ]})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation()
  .width(100).height(100).gravity("face").radius("max").crop("thumb").chain()
  .overlay(new Layer().publicId("cloudinary_icon")).effect("brightness:200").flags("relative").width(0.9).opacity(60).chain()
  .dpr(2.0)).imageTag("smiling_man.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('smiling_man.jpg', {transformation: [
  {width: 100, height: 100, gravity: "face", radius: "max", crop: "thumb"},
  {overlay: new cloudinary.Layer().publicId("cloudinary_icon"), effect: "brightness:200", flags: "relative", width: "0.9", opacity: 60},
  {dpr: "2.0"}
  ]}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("smiling_man.jpg", {transformation: [
  {width: 100, height: 100, gravity: "face", radius: "max", crop: "thumb"},
  {overlay: new cloudinary.Layer().publicId("cloudinary_icon"), effect: "brightness:200", flags: "relative", width: "0.9", opacity: 60},
  {dpr: "2.0"}
  ]})
React:
Copy to clipboard
<Image publicId="smiling_man.jpg" >
  <Transformation width="100" height="100" gravity="face" radius="max" crop="thumb" />
  <Transformation overlay="cloudinary_icon" effect="brightness:200" flags="relative" width="0.9" opacity="60" />
  <Transformation dpr="2.0" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="smiling_man.jpg" >
  <cld-transformation width="100" height="100" gravity="face" radius="max" crop="thumb" />
  <cld-transformation overlay="cloudinary_icon" effect="brightness:200" flags="relative" width="0.9" opacity="60" />
  <cld-transformation dpr="2.0" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="smiling_man.jpg" >
  <cl-transformation width="100" height="100" gravity="face" radius="max" crop="thumb">
  </cl-transformation>
  <cl-transformation overlay="cloudinary_icon" effect="brightness:200" flags="relative" width="0.9" opacity="60">
  </cl-transformation>
  <cl-transformation dpr="2.0">
  </cl-transformation>
</cl-image>
.Net:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation()
  .Width(100).Height(100).Gravity("face").Radius("max").Crop("thumb").Chain()
  .Overlay(new Layer().PublicId("cloudinary_icon")).Effect("brightness:200").Flags("relative").Width(0.9).Opacity(60).Chain()
  .Dpr(2.0)).BuildImageTag("smiling_man.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation()
  .width(100).height(100).gravity("face").radius("max").crop("thumb").chain()
  .overlay(new Layer().publicId("cloudinary_icon")).effect("brightness:200").flags("relative").width(0.9).opacity(60).chain()
  .dpr(2.0)).generate("smiling_man.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation()
  .setWidth(100).setHeight(100).setGravity("face").setRadius("max").setCrop("thumb").chain()
  .setOverlay("cloudinary_icon").setEffect("brightness:200").setFlags("relative").setWidth(0.9).setOpacity(60).chain()
  .setDpr(2.0)).generate("smiling_man.jpg")!, cloudinary: cloudinary)

DPR 1.0 circular thumbnail with a watermark

DPR 2.0 circular thumbnail with a watermark

DPR 3.0 circular thumbnail with a watermark

DPR 1.0                   DPR 2.0                                                     DPR 3.0

Now you can create a 100x100 HTML image tag and deliver an image with the resolution that best matches the specified pixel density of your users' devices.

DPR 1.0 circular thumbnail with a watermark in HTML

DPR 2.0 circular thumbnail with a watermark  in HTML

DPR 3.0 circular thumbnail with a watermark in HTML

DPR 1.0 (100x100, 4.8KB)                  DPR 2.0 (200x200, 12.8KB)                DPR 3.0 (300x300, 23.1KB)

Automatic DPR detection and delivery of best image quality using jQuery

In order to automatically serve the correct DPR version of an image to each user, you need to detect the DPR on the user's device. If your web application or mobile site is mostly dynamic and rendered on the server-side, one method is to check the User-Agent request header, and use it to set the correct DPR value of images embedded in your pages.

However, the User-Agent solution can be misleading - for example, the request header could show the user's device is a Macbook Pro Retina which has high DPR, but in fact the actual display is an external HD monitor with low DPR.

Cloudinary's jQuery plugin solves this, with client-side Javascript code that detects the actual device pixel ratio on the user's current display. Then, Cloudinary allows you to dynamically build image URLs with the best matching DPR value, and lazy-load the actual images using Javascript. You can do all this with one line of code.

Copy to clipboard
<img class="cld-hidpi"
     data-src=
"https://res.cloudinary.com/demo/image/upload/c_fill,dpr_auto,h_200,w_150/lupine.jpg"
/>

Let's explain how this works. In the image tag above, the src attribute is not set (you can set it to a placeholder blank image such as /images/blank.gif). The data-src attribute is set to a URL template of a remote image that was uploaded to Cloudinary, while cropping to a 150x200 rectangle. The URL template contains the dpr_auto directive, which allows the jQuery plugin to dynamically generate an actual image with the correct DPR value (e.g., dpr_1.0, dpr_2.0).

So - all you need to do in order to make your site responsive to retina and HiDPI screens, is to include Cloudinary's jQuery plugin in your site (see the plugin's getting started guide) and to add the following Javascript command at the end of the HTML page.

Copy to clipboard
$.cloudinary.responsive();

This method looks for all images in the page that have the cld-hidpi class, detects the device's pixel ratio, and updates the HTML image tags accordingly. Even if a user switches from Retina to non-Retina displays using the same device, correct DPR-based URLs will be generated.

You can also manually update image tags with the correct DPR-based URLs, using custom jQuery selection and applying the cloudinary_update method:

Copy to clipboard
$('img.my_dymamic_images').cloudinary_update();

Server-side rendered pages can still enjoy the automatic device pixel ratio detection on the browser-side, as shown above. When using Cloudinary's view helper methods (e.g., cl_image_tag in Ruby on Rails), you can set the new dpr parameter to auto. This creates an HTML image tag with a blank src attribute while the data-src attribute points to a dynamic image manipulation URL.

When you load Cloudinary's jQuery plugin and call $.cloudinary.responsive(); the image tags are automatically updated, and URLs are replaced with the correct DPR value. You can also set your placeholder image using the responsive_placeholder parameter, or set to the default inline blank image.

Ruby:
Copy to clipboard
<%= cl_image_tag("lupine.jpg", :width => 100, :height => 150, :crop => :fill, 
                 :dpr => :auto, :responsive_placeholder => "blank") %>
PHP:
Copy to clipboard
<?php cl_image_tag("lupine.jpg",  array("width" => 100, "height" => 150, "crop" => "fill",
                   "dpr" => "auto", "responsive_placeholder" => "blank")); ?>
Python:
Copy to clipboard
cloudinary.CloudinaryImage("lupine.jpg").image(width = 100,  height = 150,  crop = "fill", 
                   dpr = "auto", responsive_placeholder = "blank")
Node.js:
Copy to clipboard
cloudinary.image("lupine.jpg",  { width: 100, height: 150, crop: 'fill',
                   dpr: 'auto', responsive_placeholder: 'blank' })

The following HTML image tag is generated by the code samples above:

Copy to clipboard
<img class="cld-hidpi" height="150" width="100"
     data-src=
"https://res.cloudinary.com/demo/image/upload/c_fill,dpr_auto,h_150,w_100/lupine.jpg"
     src=
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"  
/>

Lupin thumbnail with dynamic DPR

Summary

Web applications and mobile sites need to become more and more responsive to support the growing variety of devices, resolutions, aspect ratios and pixel densities. It's important to deliver images of adequate quality to high resolution devices, while preventing unnecessary delivery of large images to lower resolution devices, which wastes bandwidth and harms user experience by increasing page load times.

Cloudinary's cloud-based image processing makes it easier to support retina and HiDPI devices, by performing on-the-fly generation of images and thumbnails based on a given Device Pixel Ratio. Cloudinary's SDKs for all popular development frameworks, together with client side support using a jQuery plugin, allow automatic detection of the Device Pixel Ratio of users' devices and on-the-fly delivery of images with appropriate resolution - without needing to prepare those images ahead of time.

Retina and HiDPI support is part of the larger Responsive Design challenge, and we have more features coming up that will ease the process of making your sites and apps fully responsive. More details coming soon!

Dynamic DPR detection and cloud-based image resizing is available for all of Cloudinary's plans, including our free plan. Make sure to update your Cloudinary client libraries and jQuery plugin to the latest versions. And as usual, we look forward to your thoughts and feedback on this new feature, as we develop more image management capabilities that make Responsive Design easier to implement.


Want to Learn More About Image Optimization?

Recent Blog Posts

Automation Frees Up PetRescue’s Staff to Help Pets Find Their Forever Homes

As we spend more time at home, many of us are adopting pets for the joy, companionship and a surprising range of health benefits. In Australia, where our nonprofit customer PetRescue is located, there’s a shortage of pets to adopt. Last August, the Guardian reported that dog shelters in Australia emptied and adoption fees for puppies were running as high as $AUS1800.

Read more
Cloudinary and Contentful Make Modern Content Management Easier

I am pleased to share that Cloudinary and Contentful have joined forces to further streamline the creation, processing, and delivery of online content through Cloudinary’s digital asset management (DAM) solution and advanced transformation and delivery capabilities for images and video. What’s more, the partnership delivers a headless approach to DAM. By leveraging APIs for media management tasks, marketers and developers alike benefit from an integrated stack of optimized assets for optimization and automation. As a result, page loads are fast and beautiful, and at scale—with less overhead and effort.

Read more
Introducing Cloudinary's Nuxt Module

Since its initial release in October 2016 by the Chopin brothers as a server-side framework that runs on top of Vue.js, Nuxt (aka Nuxt.js) has gained prominence in both intuitiveness and performance. The framework offers numerous built-in features based on a modular architecture, bringing ease and simplicity to web development. Not surprisingly, Nuxt.js has seen remarkable growth in adoption by the developer community along with accolades galore. At this writing, Nuxt has earned over 30K stars on GitHub and 96 active modules with over a million downloads per month. And the upward trend is ongoing.

Read more
How Quality and Quantity can go Hand in Hand

When it comes to quality versus quantity, you’ll often hear people say, “It’s the quality that counts, not the quantity”. While that’s true in many situations, there are also cases where you want both quality and quantity. You may have thousands of images on your website and you want them all to look great. This is especially important if your website allows users to upload their own content, for example, to sell their own products or services. You don't want their poor quality images to reflect badly on your brand.

Read more
Product Videos 101: What Makes Them Great?

A product’s benefits and usage, including its value proposition, features, and instructive details, are best demonstrated through video. Product-video types vary, depending on the funnel, channel, and audience, the most popular ones being demos, reviews, installation, and how-tos.

Read more