import fastapi from PIL import Image, ImageDraw, ImageFont from io import BytesIO from fastapi.responses import PlainTextResponse app = fastapi.FastAPI() img = Image.open("./smoking-caterpillar.jpg") font = ImageFont.truetype("./unicode.impact.ttf", 72) class JPEGResponse(fastapi.Response): media_type="image/jpeg" @app.get("/", response_class=PlainTextResponse) async def root(): return "go to /image for the funny thingy" @app.get("/img", response_class=JPEGResponse) async def getImage(request: fastapi.Request): img2 = img.copy() draw = ImageDraw.Draw(img2) draw.text((img2.width/2,img2.height/2), request.client.host, (255,255,255), font=font, stroke_width=5, stroke_fill=(0,0,0), anchor="mm") img_bin = BytesIO() img2.save(img_bin, format="jpeg") return fastapi.Response(content=img_bin.getvalue(), media_type="image/jpeg")