[TIPS] Convert HEIC to JPG Images Using Python
By JoeVu, at: Aug. 9, 2024, 8:36 a.m.
[TIPS] Convert HEIC to JPG Images Using Python
HEIC (High Efficiency Image Coding) is a popular image format for Apple devices, offering high-quality images with smaller file sizes. However, it might not be compatible with all applications or platforms. In this guide, we'll show you how to convert HEIC images to JPG using Python/Pillow with a simple script.
Prerequisites
Before we start, ensure you have the following Python libraries installed:
- Pillow: A powerful image-processing library.
- pillow-heif: A plugin to add HEIC support to Pillow.
You can install these libraries using pip:
pip install pillow pillow-heif
Conversion Script
Below is a Python script that converts HEIC images to JPG:
from PIL import Image
from pathlib import Path
from pillow_heif import register_heif_opener
# Register HEIC opener
register_heif_opener()
# Path to the directory containing HEIC images
images_path = Path('/Users/joe/Pictures/')
# Iterate through all HEIC files in the directory
for image_file in images_path.rglob("*.[hH][eE][iI][Cc]"):
print(f"Converting: {image_file.name}")
# Open the HEIC file
image = Image.open(image_file)
# Convert and save as JPG
new_name = f"{image_file.stem}.jpg"
image.convert('RGB').save(new_name)
print(f"Saved as: {new_name}")
Explanation
-
Library Imports: We import
Image
from Pillow for image manipulation,Path
from pathlib to handle file paths, andregister_heif_opener
frompillow-heif
to add HEIC support. -
Register HEIC Opener:
register_heif_opener()
enables Pillow to open HEIC files. -
Directory Path: We specify the directory containing HEIC images using
Path
. -
File Iteration: The script uses
rglob
to find all files with a.heic
extension in the directory. -
Image Conversion: Each HEIC file is opened, converted to RGB (necessary for JPG format), and saved as a JPG with the same name in the current directory.
Conclusion
This script efficiently converts HEIC images to JPG, making them compatible with more platforms and applications. You can customize the script to include additional features such as batch processing or saving files in a different directory.
By using Python and these powerful libraries, you can automate image conversions effortlessly. Let me know if you need further assistance or customization!