[TIPS] Convert HEIC to JPG Images Using Python

By JoeVu, at: 08:36 Ngày 09 tháng 8 năm 2024

Thời gian đọc ước tính: 3 min read

[TIPS] Convert HEIC to JPG Images Using Python
[TIPS] Convert HEIC to JPG Images Using Python

[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:

  1. Pillow: A powerful image-processing library.
     
  2. 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

  1. Library Imports: We import Image from Pillow for image manipulation, Path from pathlib to handle file paths, and register_heif_opener from pillow-heif to add HEIC support.

  2. Register HEIC Opener: register_heif_opener() enables Pillow to open HEIC files.

  3. Directory Path: We specify the directory containing HEIC images using Path.

  4. File Iteration: The script uses rglob to find all files with a .heic extension in the directory.

  5. 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!


Theo dõi

Theo dõi bản tin của chúng tôi và không bao giờ bỏ lỡ những tin tức mới nhất.