File size: 2,433 Bytes
cd95f55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
from PIL import Image
import numpy as np
from io import BytesIO
import os

app = FastAPI()

# Function for cropping and filling the image
def fill_square_cropper(img):
    imgsz = [img.height, img.width]
    avg_color_per_row = np.average(img, axis=0)
    avg_color = np.average(avg_color_per_row, axis=0)

    if img.height > img.width:
        newimg = Image.new(
            'RGB',
            (img.height, img.height),
            (round(avg_color[0]), round(avg_color[1]), round(avg_color[2]))
        )
        newpos = (img.height - img.width) // 2
        newimg.paste(img, (newpos, 0))
        return newimg

    elif img.width > img.height:
        newimg = Image.new(
            'RGB',
            (img.width, img.width),
            (round(avg_color[0]), round(avg_color[1]), round(avg_color[2]))
        )
        newpos = (img.width - img.height) // 2
        newimg.paste(img, (0, newpos))
        return newimg
    else:
        return img

@app.get("/", response_class=HTMLResponse)
def home_page():
    return """
    <html>
    <body>
    <h2>Square and Fill Image App</h2>
    <p>Upload a JPG image to square and fill with color filler.</p>
    <form action="/upload/" enctype="multipart/form-data" method="post">
        <input name="file" type="file">
        <input type="submit">
    </form>
    </body>
    </html>
    """
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):  # Make the function asynchronous
    try:
        # Await the read method
        contents = await file.read()  
        img = Image.open(BytesIO(contents)).convert("RGB")
        squared_img = fill_square_cropper(img)

        # Save the squared image
        output = BytesIO()
        squared_img.save(output, format="JPEG")
        output.seek(0)

        # Return base64-encoded image
        import base64
        encoded_img = base64.b64encode(output.getvalue()).decode("utf-8")
        return HTMLResponse(
            content=f"<h3>Image successfully squared!</h3><img src='data:image/jpeg;base64,{encoded_img}' />",
            media_type="text/html"
        )
    except Exception as e:
        return HTMLResponse(content=f"<h3>An error occurred: {e}</h3>", media_type="text/html")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))