Spaces:
Sleeping
Sleeping
import gradio as gr | |
import requests | |
from io import BytesIO | |
from PIL import Image | |
def download_image(url): | |
response = requests.get(url) | |
response.raise_for_status() | |
return Image.open(BytesIO(response.content)).convert("RGB") | |
def crop_to_aspect(img, target_ratio): | |
w, h = img.size | |
img_ratio = w / h | |
if img_ratio > target_ratio: | |
new_w = int(h * target_ratio) | |
left = (w - new_w) // 2 | |
box = (left, 0, left + new_w, h) | |
else: | |
new_h = int(w / target_ratio) | |
top = (h - new_h) // 2 | |
box = (0, top, w, top + new_h) | |
return img.crop(box) | |
def process_image(url, width, height): | |
try: | |
img = download_image(url) | |
cropped = crop_to_aspect(img, width / height) | |
final = cropped.resize((width, height), Image.LANCZOS) | |
return final | |
except Exception as e: | |
return f"Error: {str(e)}" | |
demo = gr.Interface( | |
fn=process_image, | |
inputs=[ | |
gr.Textbox(label="Image URL"), | |
gr.Number(label="Output Width (px)", value=1500), | |
gr.Number(label="Output Height (px)", value=2000) | |
], | |
outputs=gr.Image(type="pil", label="Processed Image"), | |
title="Image Crop & Resize to Target Ratio", | |
description="Downloads an image by URL, crops it to the closest 3:4 ratio (or custom ratio), and resizes to the specified output size." | |
) | |
if __name__ == "__main__": | |
demo.launch() |