How to Convert JPG to AVIF Using Python
AVIF (AV1 Image File Format) is a modern, highly efficient image format that offers superior compression compared to traditional formats like JPG or PNG. If you're looking to convert your JPG images to AVIF using Python, this guide will walk you through the process step by step.
Why Convert JPG to AVIF?
AVIF provides several advantages over JPG:
- Better Compression: AVIF files are significantly smaller while maintaining high quality.
- Support for Transparency & HDR: Unlike JPG, AVIF supports alpha transparency and high dynamic range (HDR).
- Future-Proof: AVIF is based on the AV1 video codec, making it a great choice for web and mobile applications.
Prerequisites
Before we begin, ensure you have the following installed:
- Python 3.6+ – Download from Python's official website.
- Pillow (PIL Fork) – A widely used Python imaging library.
- PyAV – A Python binding for FFmpeg, which supports AVIF encoding.
Installing Required Libraries
Run the following commands in your terminal or command prompt:
pip install pillow
pip install av
Step-by-Step Conversion Process
Step 1: Load the JPG Image
First, we'll use Pillow
to open the JPG file:
from PIL import Image
# Open the JPG image
image = Image.open("input.jpg")
Step 2: Convert to AVIF Using PyAV
Next, we'll use PyAV
to encode the image in AVIF format:
import av
# Save as AVIF
with av.open("output.avif", "w") as container:
stream = container.add_stream("av1", rate=1) # AV1 codec
frame = av.VideoFrame.from_image(image)
for packet in stream.encode(frame):
container.mux(packet)
Step 3: Verify the Output
Check the generated output.avif
file to ensure the conversion was successful.
Alternative Method: Using Pillow (Experimental)
If you're using a newer version of Pillow (v9.0+), you can try the built-in AVIF support:
image.save("output.avif", format="AVIF", quality=80)
Note: This feature is still experimental and may not work on all systems.
Conclusion
Converting JPG to AVIF in Python is straightforward with libraries like PyAV
and Pillow
. AVIF’s superior compression makes it an excellent choice for web optimisation and modern applications.
- How to convert JPG to AVIF using Python
- Best Python library for AVIF conversion
- Step-by-step guide for JPG to AVIF conversion
- AVIF vs JPG compression comparison
- How to install PyAV for Python image processing
- Python script to convert images to AVIF format
- Using Pillow for AVIF image saving
- How to reduce image size with AVIF in Python
- AVIF encoding with FFmpeg in Python
- Optimising web images with AVIF using Python
No comments:
Post a Comment