Post

Convert Images to WEBP and Generate LQIP using Python Script

Converting PNG images to WEBP format and generating LQIP (Low-Quality Image Placeholder) for fast image preview

Convert Images to WEBP and Generate LQIP using Python Script

This script converts PNG images to WEBP format and generates Low-Quality Image Placeholders (LQIP) in Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from PIL import Image
import os
import base64
import io

input_folder = "images"
output_folder = "output"
os.makedirs(output_folder, exist_ok=True)

def convert_to_webp_and_generate_lqip(input_path, output_path, output_size=(20, 20)):
    with Image.open(input_path) as img:
        # Convert the image to WEBP format
        img.save(output_path, "WEBP")
        
        # Generate LQIP in base64 format
        img.thumbnail(output_size)
        buffer = io.BytesIO()
        img.save(buffer, format="WEBP")
        buffer.seek(0)
        img_base64 = base64.b64encode(buffer.read()).decode("utf-8")
        return f"data:image/webp;base64,{img_base64}"

for filename in os.listdir(input_folder):
    if filename.lower().endswith(".png"):
        input_path = os.path.join(input_folder, filename)
        output_filename = f"{os.path.splitext(filename)[0]}.webp"
        output_path = os.path.join(output_folder, output_filename)

        # Convert and generate LQIP
        base64_image_data = convert_to_webp_and_generate_lqip(input_path, output_path)

        # Create YML tag
        yml_tag = f"""image:
  path: "/assets/img/images/{output_filename}"
  lqip: {base64_image_data}
  alt: {output_filename}"""

        print(yml_tag)

File Structure:

1
2
3
4
5
6
7
8
9
10
liqd/
├── .ipynb_checkpoints
│   └── img png to webp and liqd-checkpoint.ipynb
├── images
│   ├── img png for webp 1.png
│   └── img png for webp 2.png
├── img png to webp and liqd.ipynb
└── output
    ├── img png for webp 1.webp
    └── img png for webp 2.webp

This post shows how to convert PNG images to WEBP format and generate a base64 LQIP for faster previews.

This post is licensed under CC BY 4.0 by the author.