1

so I have some python code that generates an image inside my Flask app (can do it in JPG,PNG,etc..) and I want to display that image on my Flask app. the problem is that it needs to live in the 'static' folder, and it is 'read only' - so I can't create the image inside it. can I make the 'url_for' look inside other directories? or somehow write my image file into the 'static' folder in runtime?

davidism
  • 121,510
  • 29
  • 395
  • 339
amirzau
  • 11
  • 2

1 Answers1

2

I had a similar issue on one of my pet projects. I'm not sure if there's a better way to do it but I managed to get around it by encoding the image in base64 and passing the image tag to the html file directly via render_template(). Essentially:

import io

def serve_pil_image(pil_img):

    img_io = io.BytesIO()
    pil_img.save(img_io, 'jpeg', quality=100)
    img_io.seek(0)
    img = base64.b64encode(img_io.getvalue()).decode('ascii')
    img_tag = f'<img src="data:image/jpg;base64,{img}" class="img-fluid"/>'
    return img_tag

And in your flask app:

from PIL import Image

@app.route('/')
def index():
    my_image = Image.open(image_file)
    img_tag=serve_pil_image(my_image)
    return render_template('index.html', image=img_tag)

And in your html:

{{image|safe}}
Dharman
  • 30,962
  • 25
  • 85
  • 135