How to optimize images for websites (theoretical basis)


    Photos often take up the majority of download space on a web page and often take up significant visual space. For that reason, image optimization helps reduce a large amount of data and improve performance and improve the speed of your website:


    The less amount of data the browser needs to download, the less competition there is for the client bandwidth, plus the browser can download and render useful content faster on the screen.


    Image optimization is a combination of both art and science: art because there is no complete answer to which compression ratio is best for each particular image, and science because There are many well-developed techniques and algorithms that can significantly reduce image sizes.



    Finding the optimal settings for your images requires careful analysis in many respects: the format that can be provided, the content of the encrypted data, the quality, the size in pixels, and many others. another.



    Table of contents


    • Remove and replace the image

    • Photo Vector and Raster

    • The impact of high-resolution screens

    • Optimize vector images

    • Optimize raster images

    • Compressing image data loss and no data loss

    • Choose the right image format

    • Tools and parameter adjustments

    • Distribute the thumbnails

    • Checklist for image optimization



    Remove and replace the image


    • Eliminate unnecessary source images

    • Take advantage of CSS3 effects when possible

    • Use web fonts instead of coding text on images

    The first question you have to ask yourself is whether an image is really necessary to achieve the effect you expect. Good design is often simple and also provides the best performance.


    If you can remove images, which often require large amounts of data bytes when compared to HTML, CSS, JavaScript and other elements on the page, that's always the best optimization strategy.


    But also need to say, a beautiful image in the right place can convey more information than a thousand words, so it is up to you to find the balance.


    Next, you must consider if there is an alternative technology that can deliver the desired results, but in a more efficient way:


    • CSS effects (gradients, shadows, etc.) and the dynamic effects of CSS can be helpful in creating standalone products with resolution, which always looks sharp (Sharp) at all resolutions and zoom levels (zoom level), usually a fragment of the data required by the image file.

    • Web fonts It allows you to use beautiful fonts while retaining the ability to select, search and resize text - which significantly improves usability.

    If you ever find yourself encoding text on photos, stop and reconsider. Good typography is important for design, branding, and good readability, but the text that is frozen on the image creates a poor user experience: the text cannot be selected, cannot be searched, non-zooming, inconvenient, and user-friendly for high resolution devices (hight-DPI devices). Using web fonts requires separate optimization settings, but it addresses all of these concerns and is always a better option for displaying text.


    Photo Vector and Raster


    • Vector images are ideal for images that contain geometric shapes (geometric shapes)

    • Vector images are scalable and regardless of the resolution

    • Raster photos should be used for complex scenes with unusual shapes and high details

    Once you have determined what an image is, in fact the format needs to be optimized to get the desired effect, the next important option is to choose the appropriate format:


    Enlarged vector imagesEnlarged vector images
    Enlarged vector images
    Enlarged vector imagesRaster image enlarged
    Raster image enlarged
    • Vector images use lines, points, and polygons to represent images.

    • The raster image represents an encrypted image of the value of each pixel with a rectangular grid.

    Each format has its own strengths and weaknesses. The appropriate vector format is ideal for images that include simple geometric shapes (such as logos, text, icons, and so on), and the result is uncompromised sharpness at any point. whatever resolution and zoom level, which makes them the ideal format for high-resolution displays and components to display in various sizes.


    However, the vector format is not appropriate for complex scenes (for example, a snapshot): the number of SVG markers used to describe all the blocks can be terribly high and the output may still look unlike "photos real / photorealistic". In that case, you should use raster format images like GIF, PNG, JPEG or a newer format like JPEG-XR and WebP.


    Raster images do not have the same attractive properties as vector images, which are independent resolution and zoom - when you enlarge the raster image you will see the graphic is torn and blurred (jagged and blurry). For that reason, you may need to save multiple versions of raster images at different screen resolutions to create an optimal user experience (WordPress usually takes the initiative to do this, when you upload a large image. on it will create smaller versions of images for baby screen sizes for optimal display size).


    The impact of high-resolution screens


    • High resolution screens have multiple device pixels per CSS pixel

    • High-resolution images require significantly higher number of pixels and bytes

    • Image optimization techniques are the same regardless of the resolution

    When we talk about pixel images, we need to distinguish between different types of pixels: CSS pixels and device pixels. An individual CSS pixel can consist of many device pixels - for example, a separate CSS pixel can be directly correlated (correspond directly) with a device pixel, or may be supported by multiple device pixels. What is the problem? Yes, the more pixels the device has, the better the content displays on the screen.



    High-resolution screens (HiDPI) produce better looking results, but there's a trade-off: our images need more detail to take advantage of devices with a higher number of pixels. . The good news is, vector images are perfect for this task, as they can output any resolution The picture is still sharp - we may incur higher processing costs to produce a better detail, but the underlying image is the same and does not depend on resolution.


    Raster images, on the other hand, pose a bigger challenge, because they encode image data based on each basic pixel. Therefore, the larger the number of pixels, the greater the capacity for raster images. For example, consider the difference between images displayed at 100 x 100 (CSS) pixels:














    Screen resolutionTotal number of pixelsUncompressed file (4 bytes per pixel)
    1x100 x 100 = 10 00040 000 bytes
    2x100 x 100 x 4 = 40 000160 000 bytes
    3x100 x 100 x 9 = 90 000360 000 bytes

    When the physical screen resolution doubles, the total number of pixels will quadruple: double the number of pixels by the width, which is also double the number of pixels by the height. So doubling the screen is not just doubling the number of pixels, the number of pixels required is four times!


    So what does this mean in practice? High-resolution screens allow us to create better images, which may be an important feature of the product. However, high-resolution screens also require high-resolution images: choose vector images whenever possible so they are independent of screen resolution and always produce sharp images, and if Request raster images, create and optimize a variety of image sizes with the help of srcset and picture.


    Optimize vector images


    • SVG is an image format based on XML

    • SVG files should be minimized to reduce size

    • SVG files should be compressed with GZIP

    All modern browsers support Scalable Vector Graphics (SVG), which are XML-based image formats with two graphical aspects: we can embed SVG markup directly on the page, or as a source. outside. In contrast, an SVG file can be created by most vector drawing software, either manually or directly by your favorite drafting software.


    xml version="1.0" encoding="utf-8"?>

    version="1.2" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
       
    x="0px" y="0px" viewBox="0 0 612 792" xml:space="preserve">
    id="XMLID_1_">
     

       
    fill="red" stroke="black" stroke-width="2" stroke-miterlimit="10" cx="50" cy="50" r="40"/>
     



    The above example renders a simple circle with a black and red border color for the background and it is exported from Adobe Illustrator. As you can see, it includes a lot of metadata, like layer information, comments, and XML namespaces, which are usually unnecessary for rendering in the browser. So it is always a good idea to minimize (minify) file your SVG through a tool like svgo.


    In the example above, svgo reduces the size of SVG files created by Illustrator by 58%, reduced it from 470 to 199 bytes. Moreover, because SVG is an XML-based format, we can also apply GZIP compression to reduce transfer capacity - make sure your server is configured to have SVG compression.


    Optimize raster images


    • Raster images are a grid of pixels (grid of pixels)

    • Each pixel is color coded and has transparent attributes

    • Image compressors use a variety of techniques to reduce the number of bits required for each pixel, thereby reducing the size of the entire image.

    A raster image is simply a 2-dimensional grid of specific "pixels" - for example, a 100 x 100 pixel image is a sequence (sequence) of 10 000 pixels. In contrast, each pixel contains RGBA values: (R) red channel, (G) green channel, (B) blue channel, and (A) alpha channel (transparent property).


    Internally, the browser allocates (allocates) 256 values ​​(shades) for each channel, this will be translated into 8 bits per channel (2 ^ 8 = 256), and 4 bytes for each pixel (4 channels x 8 bits / channel = 32 bits / pixel = 4 bytes / pixel). For that reason, if we know the resolution of the grid we can easily calculate the file size:


    • 100 x 100px photos include 10 000 pixels

    • 10 000 pixels x 4 bytes = 40 000 bytes

    • 40 000 bytes / 1024 = 39 KB

    Note: no matter what the image format is used when transferring data from the server to the client, when the image is decoded by the browser, each pixel always occupies 4 bytes of memory. This can be an important limitation for large photos and devices that are not capable of providing high memory - for example, low-end mobile devices.




















    The resolutionPixelFile size
    100 x 10010 00039 KB
    200 x 20040 000156 KB
    300 x 30090 000351 KB
    500 x 500250 000977 KB
    800 x 800640 0002500 KB

    39KB for images with a resolution of 100 x 100 pixels may not seem like a big deal, but File size increases rapidly with larger images and make photo components slower and more expensive to download (if you use 3G to access the Internet will understand the price is not cheap). Fortunately, what we have just described is the "uncompressed" image format. What can we do to reduce image file size?


    A simple strategy is to reduce the "bit depth" of the image from 8 bits per channel to a smaller palette: 8 bits per channel gives 256 values ​​per channel and 16 777 216 colors all. What if we reduced the palette to 256 colors? Then we would only need 8 bits in total for the RGB channel and immediately save two bytes per pixel - that is, 50% of the compression savings compared to the original 4-byte format.



    Note: from left to right (PNG): 32-bit (16 million colors), 7-bit (128 colors), 5-bit (32 colors). Complex scenes with color gradients (gradients, sky, etc.) require large color palettes to avoid unnatural scenes (visual artifacts) as sky image pixels in 5-bit form. In other words, if the image uses only a few colors, then the large palette is simply wasting valuable bits!


    Next, once we have optimized the data stored in each specific pixel, we can be smarter and pay attention to nearby pixels: it turns out, a lot of photos, and especially photographs , adjacent pixels are the same color - for example, the sky is a textured repeater. Using this information so the compressor can apply the advantage of "delta encoding" instead of storing each specific value for each pixel, we can Store the difference between adjacent pixels: if the adjacent pixels are exactly the same, the delta is "zero", and we only need to store one bit! But why stop here ...


    The human eye has varying degrees of sensitivity to different colors: we can optimize color coding so that its capacity is reduced or increased for each color. "Adjacent" pixels have a two-dimensional grid pattern, which means that each pixel has many neighbors: we can use this fact to improve delta coding. Instead of looking immediately at the neighbors of each pixel, we can look at larger blocks of adjacent pixels and encode different blocks with different settings. And so on and so forth ...


    You can say, image optimization is increasingly complex (or in the sense of humor, depending on your point of view), and this is the area of ​​academic and commercial research. Photos take up a lot of data, so it is worth it to develop better image compression techniques! In case you're curious, go to this page on Wikipedia, or check out the WebP image compression techniques to find practical examples.


    So, again, they are all great, but also very academic: how does it help us optimize the images on our website? Yes, we are certainly not tasked with creating new compression techniques, but it is important to understand the relevant issues: RGBA pixels, bit depth, and many other optimization techniques. All of these ideas are important to understand and keep in mind before we dive into the discussion of different raster image formats.


    Compressing image data loss and no data loss


    • Because of the way the eye works, photos are great candidates for lossy image compression

    • Image compression comes in two types: data loss and data loss

    • Differences in image formats are the reason for the differences in the way data loss algorithms and data loss algorithms are used to optimize images.

    • There is no single best format or "quality setting" for all images: each combination of specific compression types and image content creates a unique output.

    For certain types of data, such as the page's source type, or an executable file, it is important that compression does not change or lose any original information: only one bit of data is lost. or wrong can change the whole meaning of the content or worse, break it completely. With some other data formats, such as photos, audio and video, it may still be fully accepted when distributing the "approximate" representation of the original data.


    In fact, due to the way our eyes work, we can eliminate some information from each pixel to reduce the size of the image size - for example, our eyes have different sensitivity levels to Different colors, which means we can use fewer bits to encode some colors. Therefore, a typical image optimization program consists of two optimization steps:


    1. An image that is processed as "losing data" means removing some pixel data

    2. The image is processed "no data loss" to compress the pixel data

    The first step is optional, and the exact algorithm will depend on the specific image format, but it's important to understand that any image can undergo lossy compression to reduce its size. In fact, the difference between many image formats, like GIF, PNG, JPEG and others, is the combination of the specific algorithms they use (or ignore) when applying lossy compression steps. Data and no data loss.


    So, what is the "optimal" option for optimizing data loss and no data loss? The answer depends on the content of your photo and your own criteria for the trade-off between file size and the loss of data compression naturally:


    In some cases you may want to bypass data loss optimization to convey complex details to get its full honesty, and in other cases you may want to apply loss optimization. Enhanced data to reduce image file size down. This is the part that you need to judge and use according to your context needs - there are no settings that are common to all.



    As a practical example, when using the lossy format for JPEGs, the compression program will often display the "quality" setting option (for example, the quality bar offers the "Save for Web" function). in Adobe Photoshop), usually a number between 1 and 100, used to adjust the inner workings of specific groups of loss and loss algorithms. To get the best results, experiment with some quality settings for your photos, and don't worry about the quality deteriorating - in fact, image quality is often still very good and capacity is pretty much saved. much.


    Note: the quality level for different image formats is not directly comparable because of the difference in the algorithm used to encode images: quality 90 for JPEG will produce a very different result than the amount of WebP. In fact, even the same level of quality for the same photo can produce different looking output images using the compression tool!


    Choose the right image format


    • Start by choosing the right overall picture format: GIF, PNG, JPEG

    • Experiment and choose the best setting for each format: quality, palette size, etc.

    • Consider adding WebP and JPEG XR formats to modern customers

    In addition to different lossless and lossless compression algorithms, different image formats support various features like animation and transparency (alpha channel). For that reason, choosing the "correct format" for a particular image is a combination of the desired graphic results and the necessary functions.


























    FormatCrystal-clearAnimationsBrowser
    GIFHaveHaveAll
    PNGHaveIs notAll
    JPEGIs notIs notAll
    JPEG XRHaveHaveIE
    WebPHaveHaveChrome, Opera, Android (*)

    (*): Update 2019, Microsoft Firefox and Edge browsers now support WebP on the desktop version.


    There are three commonly supported image formats: GIF, PNG and JPEG. In addition to these formats, some browsers also support newer formats like WebP and JPEG XR, which generally have better compression capabilities and more features. So, which format should you use?



    A. Do you need animation? If so, GIF is the only overall option.


    Palette limited GIF (color palette) up to 256 colors, which makes it a poor choice for most photos. In addition, the PNG-8 image format creates better compression ratios for images with small color palettes. For that reason, GIFs are the only right answer when you need animation.


    B. Do you need to preserve fine details with the highest resolution? Use PNG.


    • PNG does not use lossy compression algorithms that fall outside the palette's size choice. For that reason, it will produce the highest quality images, but the cost is significantly higher than other file sizes. Be wise.

    • If the image content contains geometric shapes, consider converting it to vector format (SVG)!

    • If the image includes text, stop and review. Text on images is not selectable, searchable or zoomable. If you need to use it for custom graphic purposes (for brand or other reasons), use web fonts instead.

    C. If you optimize photos, screenshots, or the like? Use JPEG.


    JPEG is a combination of lossy and lossless optimization to reduce the file size of an image. Try several JPEG quality levels to find the best tradeoff between quality & size for your photos.


    Finally, once you have determined the optimal image format and set it up for your photos, consider adding other types of coding such as WebP and JPEG XR. Both of these formats are new and unfortunately not currently fully supported by all browsers, but they can nonetheless save significant savings for new users - for example, on average, WebP creates files with 30% reduction compared to the same JPEG images.


    Because both WebP and JPEG XR are currently not supported by all browsers, you will need to add additional logic to your application or server to serve the appropriate resources:


    • Some CDN services (content delivery networks) provide image optimization as part of their services, including the distribution of JPEG XR and WebP (eg Cloudflare).

    • Some open source tools (such as PageSpeed ​​for Apache or Ngnix) automatically optimize, convert and serve the appropriate components.

    • You can add additional logic applications to detect clients, check which formats they support, and serve the best image format possible.

    Finally, note that if you use Webview to display content in your native application, then you have complete control over the client and can simply use WebP! Facebook, Google+ and many other applications use WebP to distribute their images in their respective applications - the saved space is certainly worth it. For more on WebP, see WebP Video: Faster, smaller, and more beautiful image deployment presented from Google I / O 2013.


    Tools and parameter adjustments


    No image format, tool or an optimal parameter setting is perfect for all pictures. For best results choose a format and set it depending on the content of the image, and the image quality and other required techniques.












    ToolsDescribe
    gifsiclecreate and optimize GIF images
    jpegtranOptimize JPEG images
    optipngOptimal no data loss with PNG images
    pngquantOptimize data loss with PNG images

    Don't be afraid to experiment with the parameters of each compressor. Try reducing the quality, see what it looks like, then start over and over again. Once you find a good setup team, you can apply them to other similar images on your site, but Don't expect all images to be compressed with the same settings.


    P / S: If you use WordPress, the simplest way to optimize is to use automated image compression plugins. These plugins all try to use the best compression technologies, including some of the tools just mentioned above.


    Distribute the thumbnails


    • Distributing thumbnail images is one of the simplest and most effective optimizations

    • Pay more attention to large images when their impact is often high

    • Reduce the number of unnecessary pixels by copying the images according to their display size

    Image optimization shortens to two properties: optimizes the number of bytes used to encode each pixel of the image and optimizes the total number of pixels: the size of the image is simply the total number of pixels times the total number of bytes is used to encode each pixel. Nothing more, nothing less.



    For that reason, one of the simplest and most effective techniques for image optimization is to make sure we don't load more pixels than necessary to display the image on a known browser size. Sounds simple right? Unfortunately, most sites fail the multi-image test: they typically deliver larger images and rely on the browser to resize them - this also consumes more CPU - and display them at a lower resolution.


    Note: hovering the mouse pointer over the image component in Chrome DevTools will reveal both the "display" and "natural" sizes of the image. Trong ví dụ trên ảnh có kích cỡ 300 x 260 pixel được tải về nhưng sau đó được giảm tỷ lệ xuống 245 x 212 cho người dùng khi được hiển thị.


    Khi bạn tải về Pixel dư thừa không cần thiết, rồi sau đó để trình duyệt thay đổi kích thước ảnh thay mặt chúng ta, là đánh mất cơ hội lớn để giảm và tối ưu tổng lượng bytes cần thiết để render trang. Thêm vào đó, lưu ý là thay đổi kích thước không đơn giản là chức năng của số lượng pixel mà hình ảnh được giảm bớt, mà còn là kích thước tự nhiên của nó.






























    Độ phân giải màn hìnhKích cỡ tự nhiênSize hiển thị (CSS px)Pixel không cần thiết
    1x110 x 110100 x 100110 x 110 – 100 x 100 = 2100
    1x410 x 410400 x 400410 x 410 – 400 x 400 = 8100
    1x810 x 810800 x 800810 x 810 – 800 x 800 = 16 100
    2x220 x 220100 x 100210 x 210 – (2 x 100) x (2 x 100) = 8400
    2x820 x 820400 x 400820 x 820 – (2 x 400) x (2 x 400) = 32400
    2x1620 x 1620800 x 8001620 x 1620 – (2 x 800) x (2 x 800) = 64400

    Lưu ý là trong tất cả các trường hợp ở trên, kích thước hiển thị “chỉ 10 pixel CSS nhỏ hơn” so với ảnh yêu cầu cho mỗi độ phân giải màn hình. Dầu vậy, số lượng pixels tăng thêm và các chi phí liên quan tăng lên nhanh chóng khi kích thước hiển thị của hình ảnh tăng!


    Vì lý do đó, trong khi bạn có thể không đảm bảo được mỗi ảnh sẽ được phân phối chính xác kích cỡ hiển thị, bạn phải đảm bảo số lượng pixel không cần thiết là tối thiểu, và các ảnh lớn cụ thể của bạn cần phân phối gần nhất có thể với kích cỡ hiển thị.


    Danh sách kiểm tra tối ưu hóa hình ảnh


    Một số mẹo và kỹ thuật bạn cần ghi nhớ khi làm công việc tối ưu hóa hình ảnh:


    • Ưa tiên định dạng vector: ảnh vector là độc lập với độ phân giải và tỉ lệ thu phóng, điều này làm cho chúng khớp hoàn hảo với thế giới đa thiết bị và độ phân giải cao.

    • Tối giản hóa và nén định dạng SVG: mã đánh dấu XML tạo ra bởi hầu hết các ứng dụng vẽ thường bao gồm các siêu dữ liệu không cần thiết – cái có thể loại bỏ; hãy đảm bảo rằng máy chủ của bạn được cấu hình để áp dụng nén GZIP cho ảnh SVG.

    • Chọn lấy định dạng raster tốt nhất: xác định yêu cầu chức năng của bạn và chọn lấy một cái phù hợp với từng loại cụ thể.

    • Thử nghiệm với thiết lập chất lượng tối ưu cho định dạng raster: đừng sợ hãi với cài đặt suy giảm “chất lượng”, các kết quả thường rất tốt và số lượng byte tiết kiệm được là đáng kể.

    • Loại bỏ các siêu dữ liệu không cần thiết của ảnh: nhiều ảnh raster bao gồm siêu dữ liệu không cần thiết về ảnh: thông tin địa lý, thông tin máy chụp ảnh và nhiều thứ khác. Sử dụng công cụ thích hợp để loại bỏ dữ liệu này.

    • Phục vụ hình ảnh thu nhỏ: thay đổi kích cỡ các ảnh trên máy chủ và đảm bảo rằng kích cỡ “hiển thị” gần nhất có thể với kích cỡ “tự nhiên” của ảnh. Hãy đặt sự chú ý vào các ảnh lớn cụ thể, bởi vì chúng chiếm chi phí lớn nhất khi thay đổi kích thước!

    • Tự động hóa, tự động hóa, tự động hóa: Đầu tư vào các thiết bị và cơ sở hạ tầng tự động sẽ đảm bảo cho tất cả hình ảnh của bạn luôn luôn được tối ưu.

    (Dịch từ bài viết Image Optimization – Web Fundamentals – tác giả: Ilya Grigorik – Google)




    Không có nhận xét nào