File size: 2,208 Bytes
03672ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import gradio as gr
import os
import tempfile
from PIL import Image
import pillow_heif
import numpy as np

def convert_heic_to_png(heic_file):
    """
    Convert HEIC image to PNG format with lossless compression
    
    Args:
        heic_file (str): Path to the HEIC file
        
    Returns:
        str: Path to the converted PNG file
    """
    try:
        # Register HEIF opener with Pillow
        pillow_heif.register_heif_opener()
        
        # Open the HEIC file
        img = Image.open(heic_file)
        
        # Create a temporary file for the output PNG
        with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp:
            # Save as PNG with maximum compression (lossless)
            img.save(tmp.name, 'PNG', compress_level=9)
            return tmp.name
            
    except Exception as e:
        raise gr.Error(f"Error converting HEIC to PNG: {str(e)}")

def process_heic_files(files):
    """
    Process one or more HEIC files and return download links for the converted PNGs
    """
    if not files:
        return None
        
    output_files = []
    for file in files:
        try:
            png_path = convert_heic_to_png(file.name)
            output_files.append(png_path)
        except Exception as e:
            print(f"Error processing {file.name}: {str(e)}")
    
    return output_files if output_files else None

# Create the Gradio interface
demo = gr.Interface(
    fn=process_heic_files,
    inputs=gr.File(
        file_count="multiple",
        file_types=[".heic", ".HEIC", ".heif", ".HEIF"],
        label="Upload HEIC/HEIF Files"
    ),
    outputs=gr.Files(label="Download Converted PNGs"),
    title="HEIC to PNG Converter",
    description="Upload one or more HEIC/HEIF images to convert them to lossless PNG format.",
    allow_flagging="never"
)

if __name__ == "__main__":
    # Print installation instructions if pillow_heif is not available
    try:
        import pillow_heif
    except ImportError:
        print("Error: pillow_heif is required but not installed.")
        print("Please install it using: pip install pillow-heif")
        exit(1)
        
    # Run the Gradio app
    demo.launch(share=False)