[Web] Optimize images with avif and webp format

[Web] Optimize images with avif and webp format

2023-03-24 hit count image

Let's see how to create the avif format and webp format of images by Python to fix the Serve images in next-gen formats issue of Lighthouse, and how to use lazy-load of images to fix the Defer offscreen images isue, too.

Outline

The Google Chrome browser provides a feature named Lighthouse to check the web page performance. When you use this feature, you can check the overall performance of the web page, and you can also see the problems like the following.

Optimization images - Lighthouse serve images in next-gen formats issue of images

In this blog post, I will intorduce how to optimize the image formats to fix the Serve images in next-gen formats isssue and use lazy loading of the images to fix Defer offscreen images issue.

avif and webp format

To solve the Serve images in next-gen formats problem, we need to provide the avif format and or the webp format of images. Modern browsers, excluding IE, support the avif and webp formats.

Create avif and webp format by Python

In this blot post, I will show you how to create the avif and webp formats of images from the jpg or png files by using Python.

To create the avif or webp formats of images by Python, you need to install the Pillow and pillow-avif-plugin libraries. Execute the following command to install the Pillow and pillow-avif-plugin libraries.

pip install Pillow pillow-avif-plugin

Pillow is a library to manage images in Python, and pillow-avif-plugin is a library to create the avif image format with the Pillow library.

After installing, create a file named optimization_images.py and modify it like the following.

import os
import glob
from PIL import Image
import pillow_avif

target_folder = './assets'
files = glob.glob(f'{target_folder}/**/*.jpg', recursive=True) + glob.glob(f'{target_folder}/**/*.png', recursive=True)

for f in files:
    print(f)
    title, ext = os.path.splitext(f)
    webp_file = title + '.webp'
    avif_file = title + '.avif'

    if os.path.isfile(webp_file) == False:
        img = Image.open(f)
        img.save(webp_file, format='webp')
        img.close()

    if os.path.isfile(avif_file) == False:
        img = Image.open(f)
        img.save(avif_file, format='AVIF' )
        img.close()

Let’s see the code one by one.

In my case, I store the image files to the assets folder. If you store the images to another folder, you should modify the following code.

...
target_folder = './assets'
...

Next, find all jpg and png files in the folder.

...
files = glob.glob(f'{target_folder}/**/*.jpg', recursive=True) + glob.glob(f'{target_folder}/**/*.png', recursive=True)
...

And then, change the file format by looping. To change the file name to match the file format, I prepare the file name by using os.path.

...
for f in files:
  title, ext = os.path.splitext(f)
  webp_file = title + '.webp'
  avif_file = title + '.avif'
  ...

Next, check the webp format file exists and if not, change the existing file to webp format and save it.

...
for f in files:
    ...
    if os.path.isfile(webp_file) == False:
        img = Image.open(f)
        img.save(webp_file, format='webp')
        img.close()
    ...

Also, check the avif format file exists and if not, change the existing file to avif format and save it.

...
for f in files:
    ...
    if os.path.isfile(avif_file) == False:
        img = Image.open(f)
        img.save(avif_file, format='AVIF' )
        img.close()

Done! we’ve created the Python script to change the jpg or png format image files to the avif and webp formats.

Create avif and webp file

Next, let’s create the avif and webp format files by executing the optimization_images.py file. To create the avif and webp format files, execute the following command to run the Python script.

python optimization_images.py

And then, you can see the image file list like the following and the avif and webp format files created.

...
./assets/images/category/flutter/2023/RefreshIndicator/refreshindicator_new_data_with_no_data.png
./assets/images/category/flutter/2023/RefreshIndicator/refreshindicator_pull_to_refresh.png
./assets/images/category/flutter/2023/RefreshIndicator/refreshindicator_no_data.png
./assets/images/category/flutter/2023/RefreshIndicator/listview.png
./assets/images/category/flutter/2023/RefreshIndicator/refreshindicator_refresh_no_data.png
./assets/images/category/flutter/2023/find_child_and_parent_widget/basic_app.png

picture and source tags

Let’s see how to use the avif and webp format files in web pages. To use the various format files in web pages, you need to use <picture /> and <source /> tags. Modify the image loading part to load avif and webp formats by using <picture /> and <source /> tags like the following.

<picture>
  <source srcset="example.avif" type="image/avif" />
  <source srcset="example.webp" type="image/webp" />
  <img src="example.png" alt="example file" />
</picture>

After modifying like this, the image in the format supported by the browser will be downloaded and displayed.

loading lazy

When you check the web pages has many images by Lighthouse, you can see the Defer offscreen images issues. To solve this issue, you can add loading="lazy" to the <img /> tag like the following.

<picture>
  <source srcset="example.avif" type="image/avif" />
  <source srcset="example.webp" type="image/webp" />
  <img src="example.png" alt="example file" loading="lazy" />
</picture>

If you want to know more details about loading lazy, please see the following link.

Completed

Done! we’ve seen how to create the avif and webp formats and use <picture /> and <source /> tags to optimize loading images for improving web page performance.

It’s a point that often occurs in Lighthouse, so I think it’s good to remember this optimization well this time. If you want to know about executing Lighthouse on the local or the CI environment, please see the following link.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts