Spaces:
Sleeping
Sleeping
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) | |