I'm writing an API with Flask, in which I receive an image through a POST
, and split it into tiles which I want to send back as response.
I first fetch the image, then open it as an Image
object with PIL
, and create the tiles from a cropping operation.
So far, so good.
Now I would like to send them as binaries, so as to display them in the front as explained here (although I'm not sure whether it's the best way).
I tried with flask.jsonify
, which told me that a bytes
object is not json-serializable.
Therefore, how can I send the list of the tiles created?
My route is as follows:
import io
from flask import request
from PIL import Image
from . import app
@app.route("/map/tileset/prepare", methods=['POST'])
def prepare_tileset():
image_source = request.files['image']
width = int(request.form['tileWidth'])
height = int(request.form['tileHeight'])
data = image_source.stream.read()
image_descriptor = io.BytesIO(data)
original = Image.open(image_descriptor)
tiles = []
for i in range(original.width // width):
for j in range(original.height // height):
rect = ((width)*i, (height)*j, (width)*(i+1) - 1, (height)*(j+1) - 1)
tile = original.crop(rect)
# It works until here, but I don't know what to do after
tiles.append(tile)
return tiles