AItool commited on
Commit
2974de7
·
verified ·
1 Parent(s): 3852be0

Create app.py

Browse files

square it first

Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from fastapi.responses import HTMLResponse
3
+ from PIL import Image
4
+ import numpy as np
5
+ from io import BytesIO
6
+
7
+ app = FastAPI()
8
+
9
+ # Function for cropping and filling the image
10
+ def fill_square_cropper(img):
11
+ imgsz = [img.height, img.width]
12
+ avg_color_per_row = np.average(img, axis=0)
13
+ avg_color = np.average(avg_color_per_row, axis=0)
14
+
15
+ if img.height > img.width:
16
+ newimg = Image.new(
17
+ 'RGB',
18
+ (img.height, img.height),
19
+ (round(avg_color[0]), round(avg_color[1]), round(avg_color[2]))
20
+ )
21
+ newpos = (img.height - img.width) // 2
22
+ newimg.paste(img, (newpos, 0))
23
+ return newimg
24
+
25
+ elif img.width > img.height:
26
+ newimg = Image.new(
27
+ 'RGB',
28
+ (img.width, img.width),
29
+ (round(avg_color[0]), round(avg_color[1]), round(avg_color[2]))
30
+ )
31
+ newpos = (img.width - img.height) // 2
32
+ newimg.paste(img, (0, newpos))
33
+ return newimg
34
+ else:
35
+ return img
36
+
37
+ @app.get("/", response_class=HTMLResponse)
38
+ async def home_page():
39
+ return """
40
+ <html>
41
+ <body>
42
+ <h2>Square and Fill Image App</h2>
43
+ <p>Upload a JPG image to square and fill with color filler.</p>
44
+ <form action="/upload/" enctype="multipart/form-data" method="post">
45
+ <input name="file" type="file">
46
+ <input type="submit">
47
+ </form>
48
+ </body>
49
+ </html>
50
+ """
51
+
52
+ @app.post("/upload/")
53
+ async def upload_file(file: UploadFile = File(...)):
54
+ contents = await file.read()
55
+ img = Image.open(BytesIO(contents)).convert("RGB")
56
+ squared_img = fill_square_cropper(img)
57
+
58
+ # Save the squared image
59
+ output = BytesIO()
60
+ squared_img.save(output, format="JPEG")
61
+ output.seek(0)
62
+
63
+ return HTMLResponse(content=f"<h3>Image successfully squared!</h3><img src='data:image/jpeg;base64,{output.getvalue().hex()}' />", media_type="text/html")