Spaces:
Paused
Paused
File size: 1,553 Bytes
4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 6404d3f 4b945f4 | 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 | from fastapi import FastAPI
from fastapi.responses import Response
from PIL import Image, ImageDraw, ImageFont
import io
import textwrap
app = FastAPI()
@app.get("/")
def home():
return {
"creator": "Muhammad Farel",
"endpoint": "/ustadz?text=halo"
}
@app.get("/ustadz")
def ustadz(text: str = "Contoh Soalan"):
img = Image.open("template.jpg").convert("RGB")
draw = ImageDraw.Draw(img)
width, height = img.size
# area kotak putih (sesuaikan kalau perlu)
box_x1 = 200
box_y1 = 150
box_x2 = width - 200
box_y2 = 450
box_width = box_x2 - box_x1
box_height = box_y2 - box_y1
# cari font terbesar yang muat
font_size = 80
while font_size > 20:
font = ImageFont.truetype("DejaVuSans-Bold.ttf", font_size)
lines = textwrap.wrap(text, width=25)
total_height = 0
for line in lines:
bbox = draw.textbbox((0,0), line, font=font)
total_height += bbox[3] - bbox[1] + 10
if total_height <= box_height:
break
font_size -= 2
# posisi tengah vertikal
y = box_y1 + (box_height - total_height) / 2
for line in lines:
bbox = draw.textbbox((0,0), line, font=font)
text_width = bbox[2] - bbox[0]
x = box_x1 + (box_width - text_width) / 2
draw.text((x,y), line, fill="black", font=font)
y += (bbox[3] - bbox[1]) + 10
buffer = io.BytesIO()
img.save(buffer, format="PNG")
return Response(buffer.getvalue(), media_type="image/png") |