Search code examples
pythonpython-imaging-librarybottle

Python - Bottle & Pillow - Return image to browser


I use Bottle Framework and Pillow, I want to generate an image on the fly and display it to the browers using the endpoint.

I have :

try:
    img = Image.open("images/template.png")
    
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("fonts/arial.ttf", 40)
    
    draw.text((23, 62), "Text", "#000", font=font)
    
    # image save works
    img.save("test_save.png")
    
    response.content_type = 'image/png'
    
    return io.BytesIO(img.tobytes())
except OSError as exception:
    print(exception)
    pass

The image saved is perfect, but the image displayed to browser is only an empty square with bad dimensions.

I looked at Stackoverflow to find what I wrote, but I guess I missed something ?


Solution

  • I'm not at a computer to test my code, but you need to return a PNG-encoded image, so you need to tell PIL to write into a BytesIO rather than to disk. Something like:

    from io import BytesIO
    
    # Write PIL Image to in-memory PNG
    membuf = BytesIO()
    img.save(membuf, format="png") 
    

    ... you can now send membuf.getvalue() and if you check the first few bytes they will look exactly the same as if you dump any other, regular PNG file from your disk.