File size: 4,082 Bytes
2974de7
 
 
c3f998c
2974de7
c3f998c
 
3607789
2974de7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3f998c
2974de7
495811a
2974de7
 
 
 
c3f998c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2974de7
 
 
 
 
c3f998c
2974de7
 
 
c3f998c
2974de7
c3f998c
fe496f4
c3f998c
 
fe496f4
 
 
 
 
 
 
2974de7
fe496f4
 
 
 
 
 
 
 
2974de7
495811a
 
 
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
import numpy as np
from PIL import Image
from io import BytesIO
import requests
import base64
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

# Home Page
@app.get("/", response_class=HTMLResponse)
def home_page():
    return """
    <html>
    <body>
    <h2>Square and Fill Image App</h2>
    <p>Select a tab below:</p>
    <ul>
        <li><a href="/demo">Demo</a></li>
        <li><a href="/application">Application</a></li>
    </ul>
    </body>
    </html>
    """

# Demo Page
@app.get("/demo", response_class=HTMLResponse)
def demo_page():
    # URLs for demo images
    url1 = "https://raw.githubusercontent.com/webdevserv/images_video/main/cowportrait.jpg"
    url2 = "https://raw.githubusercontent.com/webdevserv/images_video/main/cowlandscape.jpg"

    # Process the first image
    response = requests.get(url1)
    img1 = Image.open(BytesIO(response.content)).convert("RGB")
    squared_img1 = fill_square_cropper(img1)
    output1 = BytesIO()
    squared_img1.save(output1, format="JPEG")
    encoded_img1 = base64.b64encode(output1.getvalue()).decode("utf-8")

    # Process the second image
    response = requests.get(url2)
    img2 = Image.open(BytesIO(response.content)).convert("RGB")
    squared_img2 = fill_square_cropper(img2)
    output2 = BytesIO()
    squared_img2.save(output2, format="JPEG")
    encoded_img2 = base64.b64encode(output2.getvalue()).decode("utf-8")

    return f"""
    <html>
    <body>
    <h2>Square Image Demo</h2>
    <p>Image will be squared with color filler where applicable.</p>
    <h3>Result 1:</h3>
    <img src="data:image/jpeg;base64,{encoded_img1}" />
    <h3>Result 2:</h3>
    <img src="data:image/jpeg;base64,{encoded_img2}" />
    <a href="/">Back to Home</a>
    </body>
    </html>
    """

# Application Page
@app.get("/application", response_class=HTMLResponse)
def application_page():
    return """
    <html>
    <body>
    <h2>Square Image Application</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>
    <a href="/">Back to Home</a>
    </body>
    </html>
    """

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    try:
        # Await file upload
        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
        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)))