32 lines
1.0 KiB
Python
32 lines
1.0 KiB
Python
from fastapi import FastAPI, Response
|
|
from PIL import Image
|
|
import io
|
|
|
|
app = FastAPI()
|
|
|
|
@app.get(
|
|
"/",
|
|
|
|
# Set what the media type will be in the autogenerated OpenAPI specification.
|
|
# fastapi.tiangolo.com/advanced/additional-responses/#additional-media-types-for-the-main-response
|
|
responses = {
|
|
200: {
|
|
"content": {"image/png": {}}
|
|
}
|
|
},
|
|
|
|
# Prevent FastAPI from adding "application/json" as an additional
|
|
# response media type in the autogenerated OpenAPI specification.
|
|
# https://github.com/tiangolo/fastapi/issues/3258
|
|
response_class=Response,
|
|
)
|
|
|
|
def get_image():
|
|
image = Image.new('RGB', (1000, 1000), (100,200,10))
|
|
imgByteArr = io.BytesIO()
|
|
# image.save expects a file as a argument, passing a bytes io ins
|
|
image.save(imgByteArr, format="PNG")
|
|
# Turn the BytesIO object back into a bytes object
|
|
imgByteArr = imgByteArr.getvalue()
|
|
# media_type here sets the media type of the actual response sent to the client.
|
|
return Response(content=imgByteArr, media_type="image/png") |