How to Convert JPG to HEIF Using Python
HEIF (High Efficiency Image Format) is a modern image format that offers better compression and quality compared to traditional formats like JPG. If you're looking to convert JPG images to HEIF using Python, this guide will walk you through the process step by step.
Why Convert JPG to HEIF?
HEIF provides several advantages over JPG:
- Better compression (smaller file size with similar or better quality).
- Support for transparency, animations, and multiple images in a single file.
- Wider colour gamut and higher dynamic range.
Prerequisites
Before we begin, ensure you have the following installed:
- Python 3.6 or later.
- The
pillow-heif
library, which is a popular Python module for HEIF conversion.
Install the required library using pip:
pip install pillow pillow-heif
Step-by-Step Conversion Process
Step 1: Import Required Libraries
First, import the necessary modules in your Python script:
from PIL import Image
import pillow_heif
Step 2: Load the JPG Image
Use the Image.open()
method to load your JPG file:
jpg_image = Image.open("input.jpg")
Step 3: Convert and Save as HEIF
Use the pillow_heif
library to save the image in HEIF format:
heif_image = pillow_heif.from_pillow(jpg_image)
heif_image.save("output.heif", quality=90) # Adjust quality as needed (1-100)
Note: The quality
parameter controls the compression level (higher values mean better quality but larger file size).
Complete Python Script
Here’s the full script for converting JPG to HEIF:
from PIL import Image
import pillow_heif
def convert_jpg_to_heif(input_path, output_path, quality=90):
# Open the JPG image
jpg_image = Image.open(input_path)
# Convert to HEIF
heif_image = pillow_heif.from_pillow(jpg_image)
# Save the HEIF file
heif_image.save(output_path, quality=quality)
print(f"Successfully converted {input_path} to {output_path}")
# Example usage
convert_jpg_to_heif("input.jpg", "output.heif")
Troubleshooting Tips
- If you encounter errors, ensure
pillow-heif
is properly installed. - Some older devices may not support HEIF. Check compatibility before widespread use.
- For batch conversion, loop through multiple files using
os.listdir()
.
- How to convert JPG to HEIF using Python
- Best Python library for HEIF conversion
- Step-by-step guide for JPG to HEIF conversion
- Python script for image format conversion
- How to use pillow-heif for HEIF files
- Convert multiple JPGs to HEIF in Python
- HEIF vs JPG compression comparison
- How to reduce image size with HEIF in Python
- Python code for batch image conversion
- How to install pillow-heif for HEIF support
No comments:
Post a Comment