|
import os |
|
import zipfile |
|
import tempfile |
|
from PIL import Image |
|
import gradio as gr |
|
import shutil |
|
|
|
def resize_icons(zip_file_path, width, height): |
|
import uuid |
|
|
|
valid_extensions = (".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp") |
|
|
|
|
|
with tempfile.TemporaryDirectory() as tmpdir: |
|
|
|
extract_dir = os.path.join(tmpdir, "extracted") |
|
os.makedirs(extract_dir, exist_ok=True) |
|
|
|
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref: |
|
zip_ref.extractall(extract_dir) |
|
|
|
|
|
output_dir = os.path.join(tmpdir, "resized") |
|
os.makedirs(output_dir, exist_ok=True) |
|
|
|
files_processed = 0 |
|
|
|
|
|
for root, _, files in os.walk(extract_dir): |
|
if "__MACOSX" in root: |
|
continue |
|
|
|
for file in files: |
|
if not file.lower().endswith(valid_extensions): |
|
continue |
|
if file.startswith("._"): |
|
continue |
|
|
|
file_path = os.path.join(root, file) |
|
try: |
|
img = Image.open(file_path) |
|
img = img.convert("RGBA") |
|
img_resized = img.resize((int(width), int(height)), Image.LANCZOS) |
|
|
|
|
|
rel_path = os.path.relpath(file_path, extract_dir) |
|
output_path = os.path.join(output_dir, rel_path) |
|
os.makedirs(os.path.dirname(output_path), exist_ok=True) |
|
img_resized.save(output_path) |
|
files_processed += 1 |
|
except Exception as e: |
|
print(f"Skipping {file_path}: {e}") |
|
|
|
if files_processed == 0: |
|
raise FileNotFoundError("No valid image files found to resize.") |
|
|
|
|
|
unique_id = uuid.uuid4().hex |
|
final_zip_path = f"/tmp/resized_icons_{unique_id}.zip" |
|
|
|
with zipfile.ZipFile(final_zip_path, 'w') as zipf: |
|
for root, _, files in os.walk(output_dir): |
|
for file in files: |
|
full_path = os.path.join(root, file) |
|
arcname = os.path.relpath(full_path, output_dir) |
|
zipf.write(full_path, arcname) |
|
|
|
return final_zip_path |
|
|
|
|
|
demo = gr.Interface( |
|
fn=resize_icons, |
|
inputs=[ |
|
gr.File(label="Upload ZIP of Icons", file_types=[".zip"]), |
|
gr.Number(label="Width", value=64), |
|
gr.Number(label="Height", value=64) |
|
], |
|
outputs=gr.File(label="Download Resized ZIP"), |
|
title="📦 Icon Resizer", |
|
description="Upload a ZIP of images (icons). Set width and height. Download resized icons as a ZIP." |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |