Images are essential for all websites. Whether it is product images for an e-commerce store, photographs of picturesque locations on a travel website or images to support the content of a blog.
While they help communicate a lot more than just plain text, images are huge in terms of the bandwidth utilized. So much so, that images make up for almost 60% of the page weight of an average page on the internet. And because images are so heavy, to ensure a fast page load time, we go to great lengths to ensure that they are always optimized - compressed, in the right format and the right size.
我需要做更多的图像优化吗? ( Do I need to do more with image optimization? )
YES.
是。
In the last 10 years, the number of smartphones and similar devices has grown manifold. Combine that with cheaper and more accessible data plans, more and more people have started accessing the internet from mobile devices.
Therefore, we need to optimize our website, including the images as well, not just for our desktop users, but more importantly, for our mobile users, including the new devices with different screen sizes and resolutions that get introduced every year.
Basic HTML and CSS - To create a responsive web page and the styles for it 基本HTML和CSS-创建响应式网页及其样式
ImageKit.io - It is a CDN-enabled automatic image optimization server that also allows you to transform (resize, crop, blur, watermark and more) images in real-time with just a few minutes of setup. The workflow for delivering responsive images becomes significantly simple with real-time resizing. ImageKit.io-这是一个启用CDN的自动图像优化服务器,它还允许您仅需几分钟的设置就可以实时转换(调整大小,裁剪,模糊,水印等)图像。 通过实时调整大小,用于传递响应图像的工作流程变得非常简单。
In the examples that follow, we make use of images uploaded to the media library of a demo account created on ImageKit.
在以下示例中,我们利用上载到在ImageKit上创建的模拟帐户的媒体库的图像 。
什么是响应式图像? ( What are responsive images? )
If we keep desktop devices in mind, an 800px width image would be great. However, a mobile screen requires only a 360px width image and any image significantly wider than this would consume a lot of unnecessary bandwidth. If we do the opposite, i.e. load a smaller width image on desktop devices, then it appears grainy when stretched to fit the layout on a desktop screen.
The ideal solution would be to have our images “respond” differently (or load differently) for different devices. This method of loading images is known as responsive images.
In this article, we restrict ourselves to the img tag in HTML for our discussion related to responsive images.
在本文中,我们将自己限制在HTML中的img标签上,以进行有关响应式图像的讨论。
Typically, the image tag looks like this
通常,图片标签如下所示
The src attribute of the img tags allows us to specify only one image URL for our web page. However, there are two more attributes of the img tag which allow us to create responsive images. These have been discussed later in this post.
First, let’s try to mimic a real-life use case - a product listing page on an e-commerce website. Typically on mobile devices, we would follow a one-column layout for the products (images occupy 100% of the screen width), on tablet devices, a two-column layout (images occupy 50% of screen width) and on desktop devices, a three-column layout (images occupy almost 33% of viewport width).
Here is a code demo for this layout using the img tag with just the src attribute
这是仅使用src属性的img标签用于此布局的代码演示
On both desktop and mobile devices, the same original image gets loaded, which is not the right thing to do.
在台式机和移动设备上,都加载了相同的原始图像,这不是正确的选择。
如何切换到响应图像? ( How to switch to responsive images? )
As mentioned earlier, the img tag provides us with two attributes that allow us to deliver responsive images to our users. These attributes are srcset and sizes.
Before we discuss in detail about the use of these two image attributes, let’s look at how does our HTML change for the above example.
在详细讨论这两个图像属性的使用之前,让我们看一下上面示例中HTML如何更改。
srcset和size属性是什么,浏览器如何使用它们? ( What are the srcset and sizes attributes and how does a browser use them? )
To load the right image on particular screen size, we need to have the following data
要在特定屏幕尺寸上加载正确的图像,我们需要以下数据
The device dimensions - what is the device width? 设备尺寸-设备宽度是多少?
The layout - what is the size occupied by a particular image for the current device width? 布局-当前设备宽度下,特定图像占用的大小是多少?
The appropriate image needed to fit the current layout - the image URL 符合当前布局所需的适当图像-图像URL
The srcset and sizes attributes help answer these questions in the HTML.
srcset和sizes属性有助于在HTML中回答这些问题。
The browser already knows the device width. Then the sizes attribute, written similar to CSS media queries, specifies the layout for the image for different device widths.
For example, from the sizes attribute in the responsive image tag above, if the device width is less than 480px (a mobile device), the image occupies the full viewport width (100vw). If the device width is less than 720px, the image occupies 50% of the viewport width (50vw), and for all other cases (desktop devices), the image occupies 33% of the viewport width (33vw).
The srcset attribute, on the other hand, provides a comma-separated list of image URLs that the browser can use for different layouts along with their actual pixel width.
For example, from the responsive image tag above, we provide the browser with 3 image URLs and their corresponding absolute widths. We take advantage of ImageKit’s real-time image resizing here. Using the width transformation (specified using w parameter), we are able to generate different sizes of an image in real-time.
The image URL https://ik.imagekit.io/demo/resp-img/image1.jpg?tr=w-320 is 320px wide and we communicate this absolute width to the browser using 320w after the image URL. Similarly https://ik.imagekit.io/demo/resp-img/image1.jpg?tr=w-480 is 480px wide (width specified to the browser using 480w)and https://ik.imagekit.io/demo/resp-img/image1.jpg?tr=w-720 is 720px wide (width specified to the browser using 720w).
Here is how the browser evaluates which image to load on a device with width 400px
这是浏览器如何评估在宽度为400px的设备上加载哪个图像的方法
Device width is 400px which is less than 480px (the first rule that matches in set specified by sizes attribute), so the image occupies 100% of the viewport width (100vw) 设备宽度为400像素,小于480像素(第一个匹配sizes属性指定的集合中的规则),因此图像占据了视口宽度( 100vw )的100%
Which means that I need a 400px wide image. 这意味着我需要一个400px宽的图像。
The closest size, that is also larger than the required 400px width, from the srcset attribute is https://ik.imagekit.io/demo/resp-img/image1.jpg?tr=w-480 which is 480px wide as per the srcset specification. srcset属性中最接近的尺寸(也大于所需的400px宽度)为https://ik.imagekit.io/demo/resp-img/image1.jpg?tr=w-480 ,其宽度为480px srcset规范。
Let’s load this image. 让我们加载此图像。
响应图像的示例代码和浏览器行为 ( Example code and browser behavior with responsive images )
Here is a sample code that uses responsive images using the srcset and sizes attributes. Note that the CSS remains the same for both the cases, normal vs. responsive images, only the img tag in the HTML changes.
From the screenshot below, that is taken at a viewport width of 719px, the browser automatically triggers loads for 480px wide images (note tr=w-480 in all the requests in the network panel). Also, ImageKit automatically converted them to WebP ensuring even smaller image size and faster load.
On the other hand, for a desktop device, the browser automatically triggers loads for 720px wide images.
另一方面,对于台式设备,浏览器会自动触发720px宽图像的加载。
An important thing to note here is that if the browser has already loaded a larger image, even on browser resize, it is not going to trigger a request for a smaller image. In such cases, it is better to resize the image on the browser-side, than to issue another request over the network.
如何构建高密度显示器? ( How to build for high-density displays? )
Modern laptops and mobile devices like the MacBooks and the iPhones have high-density displays. While it is a lengthy topic in itself, a simplistic explanation would be, that for a high-density display you would need to load a larger image than a standard display, taking into account the pixel density of the high-density display.
DPR or Device Pixel Ratio is the multiplier used to specify the screen density. For example, if a high-density display has a DPR of 2, then you need to load twice the image size as compared to a standard screen for the same visual sharpness.
There can be cases where we don’t have a responsive website and instead have a separate desktop and a separate mobile website. In such a case, we don’t need different image sizes for different screen widths, but we still want to cater to multiple DPR values (a high-density screen of MacBook Pro vs. a standard screen of any other laptop - same width, but different DPR).
Here is an example where we provide different image URLs for different DPR values. We use ImageKit’s dpr transform to deliver images for different DPR values. Note that we use 1x, 2x and 3x to specify the size multiplier used for each image.
The browser automatically picks up the most appropriate image from the list specified in the srcset attribute depending on the DPR value of the device. For example, if the DPR is 2, then the browser uses the 2x image.
Here is a live demo of responsive images to support multiple screen densities
这是响应式图像的实时演示,可支持多种屏幕密度
艺术指导-使响应式图像更有意义 ( Art Direction - Making responsive images more meaningful )
In previous examples, we were able to load different images for different screen sizes and different DPR values. However, we were loading the resized versions of the same image.
Different devices may not just need different sizes of the same image but may be different images altogether to make the visual experience even better. Let’s take a look at the example below -
In this example, the image used on desktop devices contains the complete landscape along with the girl on the swing in the center. On mobile, if we use just a simple resize of the original image, then the subject of the image (the girl on the swing) becomes too small and may not have the effect intended from the image.
In such cases, we need to use a different image, where we crop a smaller, tighter region around the girl and use that for smaller screens. This art direction, utilizing different images on different devices, makes the subject stand out.
如何获得不同的艺术指导图像? ( How do I get different images for art direction? )
For art direction, the first step is to get a tighter crop image for the smaller screen. ImageKit makes this simple with its smart crop transformation. It automatically focuses on the most crucial part of the image to create the output image. Here is the smart crop transform in action
With ImageKit’s Smart Crop (with fo-auto parameter for auto focus) - https://ik.imagekit.io/demo/resp-img/tr:w-200,h-400,fo-auto/responsive_images/image1_BJona-M_4.jpg
The next step is to use the more powerful picture tag instead of the srcset and sizes attribute. This tag allows you to provide more complex specifications for which image to load, than what is possible using the srcset and sizes attributes. Here is how the updated picture tag looks like with art direction.
Inside the picture tag, the source tag is used to provide the specification for the img tag. For desktop screens (more than width 1081px) we use ImageKit’s real-time resizing to deliver an image with width 800px, whereas for tablet and other devices we use a smart-cropped image obtained using ImageKit.
A working demo with art direction can be found here
可在此处找到具有艺术指导的工作演示
Here is a comparison of the same page and layout, with and without art direction. Clearly, with art direction, the subject of the image stands out in the final image.
Responsive images are essential for your websites. Combined with art direction, not only do they help in building a better visual experience for your users but also ensure that you are not loading any extra bytes on the page than what is needed.
ImageKit makes delivering responsive images even simpler with real-time URL-based resize and smart crop allowing us to generate different image sizes needed for different devices. Thereby, eliminating any manual efforts in building a responsive image experience (except for making the HTML changes ). Additionally, ImageKit automatically delivers images in the correct format (including WebP image format) using a CDN, ensuring the lightest and fastest possible delivery of all your images.
So, go ahead and get started with ImageKit. It starts free for up to 20GB bandwidth every month! Just a few minutes to integrate with your existing images and you are ready to deliver a great visual experience on your website.