File size: 1,403 Bytes
b489c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()