| import os |
| from datetime import datetime |
| from PIL import Image |
| from pillow_heif import register_heif_opener |
|
|
|
|
|
|
| def read_files(dir_path): |
| try: |
| |
| dir_path = os.path.abspath(dir_path) |
| print(f"Checking directory: {dir_path}") |
| |
| |
| if not os.path.isdir(dir_path): |
| raise ValueError(f"Directory {dir_path} does not exist") |
| |
| |
| if not os.access(dir_path, os.R_OK): |
| raise PermissionError(f"No read permission for directory {dir_path}") |
| |
| files_info = [] |
| |
| print (dir_path) |
| all_files=os.scandir(dir_path) |
| |
| for entry in all_files: |
| if entry.is_file(): |
| try: |
| mod_time = datetime.fromtimestamp(entry.stat().st_mtime) |
| files_info.append(entry.name) |
| |
| except Exception as e: |
| print(f"Error processing file {entry.name}: {str(e)}") |
| |
| if not files_info: |
| print(f"No files found in directory {dir_path}") |
| |
| |
| files_info.sort(key=lambda x: x[1], reverse=True) |
| print (len(files_info)) |
| return files_info |
| |
| except Exception as e: |
| print(f"Error accessing directory {dir_path}: {str(e)}") |
| return [] |
|
|
|
|
|
|
|
|
| def convert_heic_to_jpg(input_image_path): |
| """ |
| Convert a .heic image to JPEG format and delete the original .heic file. |
| Args: |
| input_image_path (str): Path to the input .heic file. |
| Returns: |
| str: Path to the output JPEG file, or None if conversion fails. |
| """ |
| try: |
| |
| input_image_path = os.path.abspath(input_image_path) |
| print(f"Processing file: {input_image_path}") |
|
|
| |
| if not os.path.isfile(input_image_path): |
| print(f"Error: File '{input_image_path}' does not exist") |
| return None |
|
|
| |
| if not input_image_path.lower().endswith('.heic'): |
| print(f"Error: File '{input_image_path}' is not a .heic file") |
| return None |
|
|
| |
| register_heif_opener() |
|
|
| |
| img = Image.open(input_image_path) |
| print(f"Image opened: {img.size}, {img.mode}") |
|
|
| |
| output_image_path = os.path.splitext(input_image_path)[0] + '.jpg' |
|
|
| |
| img_rgb = img.convert('RGB') |
| img_rgb.save(output_image_path, format='JPEG', quality=95) |
| print(f"Converted {input_image_path} to {output_image_path}") |
|
|
| |
| try: |
| os.remove(input_image_path) |
| print(f"Deleted original file: {input_image_path}") |
| except Exception as e: |
| print(f"Error deleting {input_image_path}: {str(e)}") |
| |
| return output_image_path |
|
|
| return output_image_path |
|
|
| except Exception as e: |
| print(f"Error converting {input_image_path}: {str(e)}") |
| return None |