Pass Images to HTML Without Saving Them as Files Using Python Flask.

Burak Şenol
2 min readOct 18, 2020
Pass Images to HTML Without Saving Them as Files

In today’s article, I will show you a short but very effective image transfer method for those who develop image processing and similar apps using Flask micro framework.

The file read-write procedure used to transfer images created in the Python Back-end to the Front-end can sometimes cause problems and run slowly. In addition, some cloud services do not allow you to write files to your web applications running on free tier accounts.(Heroku Free Dynos)

If you have experienced one of the problems mentioned above, the method described below may be your solution.

First of all, let’s specify the libraries we will use in this example.

  • Flask
  • PIL
  • base64
  • io

After the installation of the libraries we will use, we need a Flask micro framework web app template.

  • Due to its usage, our file structure will be as follows.
File Structure of Simple Flask Web App
  • Quickstart Code Snippet.
Python Flask QuickStarter Template

You can watch this video to learn more detailed usage info about Python Flask micro framework.

Everything is ready to implement our method.

  • Now we select the image that we will transfer to the front-end html and read it with the help of PIL.
Python PIL Read Image
  • Then, using BytesIO we get the in-memory info to save the image we just read.
BytesIO

BytesIO
Just like what we do with variables, data can be kept as bytes in an in-memory buffer when we use the io module’s Byte IO operations.

  • We use the in-memory info we get using BytesIO in the save() function inside the PIL library.
  • Finally, we use base64encode to transfer the image we saved as in-memory to html.
File saving and encoding process

After the above processes, our image is now ready to be transferred into html.

  • Using Flask “render_template”, we transfer the encoded image to html.
  • Then we show the image on front-end html using the jinja variable in the html tag below.
Full Script
index.html file With JinJa variable in it

Result

index.html

Thanks for reading. See you at next post :)

--

--