Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
from io import BytesIO
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
def download_image(url):
|
7 |
+
response = requests.get(url)
|
8 |
+
response.raise_for_status()
|
9 |
+
return Image.open(BytesIO(response.content)).convert("RGB")
|
10 |
+
|
11 |
+
def crop_to_aspect(img, target_ratio):
|
12 |
+
w, h = img.size
|
13 |
+
img_ratio = w / h
|
14 |
+
|
15 |
+
if img_ratio > target_ratio:
|
16 |
+
new_w = int(h * target_ratio)
|
17 |
+
left = (w - new_w) // 2
|
18 |
+
box = (left, 0, left + new_w, h)
|
19 |
+
else:
|
20 |
+
new_h = int(w / target_ratio)
|
21 |
+
top = (h - new_h) // 2
|
22 |
+
box = (0, top, w, top + new_h)
|
23 |
+
|
24 |
+
return img.crop(box)
|
25 |
+
|
26 |
+
def process_image(url, width, height):
|
27 |
+
try:
|
28 |
+
img = download_image(url)
|
29 |
+
cropped = crop_to_aspect(img, width / height)
|
30 |
+
final = cropped.resize((width, height), Image.LANCZOS)
|
31 |
+
return final
|
32 |
+
except Exception as e:
|
33 |
+
return f"Error: {str(e)}"
|
34 |
+
|
35 |
+
demo = gr.Interface(
|
36 |
+
fn=process_image,
|
37 |
+
inputs=[
|
38 |
+
gr.Textbox(label="Image URL"),
|
39 |
+
gr.Number(label="Output Width (px)", value=1500),
|
40 |
+
gr.Number(label="Output Height (px)", value=2000)
|
41 |
+
],
|
42 |
+
outputs=gr.Image(type="pil", label="Processed Image"),
|
43 |
+
title="Image Crop & Resize to Target Ratio",
|
44 |
+
description="Downloads an image by URL, crops it to the closest 3:4 ratio (or custom ratio), and resizes to the specified output size."
|
45 |
+
)
|
46 |
+
|
47 |
+
if __name__ == "__main__":
|
48 |
+
demo.launch()
|