How to display a bytes type image in HTML/Jinja2 template using FastAPI?

Kaiss B.

I have a FastAPI app that gets an image from an API. This image is stored in a variable with type: bytes.

I want to display the image in HTML/Jinja2 template (without having to download it). I followed many tutorials but couldn't find the solution.

Here is what I came up with so far:

@app.get("/{id}")
async def root(request: Request, id: str):
    picture = await get_online_person()

    data = base64.b64encode(picture)  # convert to base64 as bytes
    data = data.decode()  # convert bytes to string

    # str_equivalent_image = base64.b64encode(img_buffer.getvalue()).decode()
    img_tag = '<img src="data:image/png;base64,{}">'.format(data)
    return templates.TemplateResponse(
        "index.html", {"request": request, "img": img_tag}
    )

All I get in the HTML is this: (as text on the page, not from source code)

    <img src="data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAQECAQEBAgICAgICAgICAQICAgICAgICAgL/2wBDAQEBAQEBAQEBAQECAQEBAgICAgI
CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgL/wgARCAQABAADASIAA
hEBAxEB/8QAHgAAAQUBAQEBAQAAAAAAAAAABQIDBAYHAQgACQr/xAAcAQACAwEBAQEAAAAAAAAAAAACAwABBAUGBwj/2gAMAwEAAhADEAAAAfEpwSR+a+9IPR3c7347iwscmWyYchEIJjn+MbJj/c4FFbbb9J5....................

Note: For people who are marking my question to a duplicate talking about urllib, I cannot use urllib because the image I'm getting is from ana API, and using their direct url will result in a 403 Forbidden, so I should use their python API to get the image.

Chris

As shown in the last section of this answer, on server side, you should return only the base64-encoded string using TemplateResponse:

# ...
base64_encoded_image = base64.b64encode(image_bytes).decode("utf-8")
return templates.TemplateResponse("index.html", {"request": request,  "myImage": base64_encoded_image})

On client side, you could display the image as follows:

<img src="data:image/jpeg;base64,{{ myImage | safe }}">

Alternative approaches can be found here.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to convert an image into 2d array of its bytes, and then back to an image using the same array?

How can one display an image using cv2 in Python

How to Display HTML Table Using Golang Template

how to display image to template from imagefield in django

How to display database image (bytes[]) in mvc WebGrid

How to display an image stored in SQL Server field using image data type?

How to display template parameter type name in natvis?

How to convert image which type is bytes to numpy.ndarray?

unable to display Image in a Django Template (using ImageField)

How to encode OpenCV Image as bytes using Python

How to get value of input type = image and display it on image?

python: how to display a image directly from bytes string variable?

display image from django model to template using for loop

How to return an image in fastAPI

Display image in Template

How to display image inside gridview template field without using handler class?

How display dummy image if return type of api is "no Image" using angualrJs?

How can i convert type IPython.core.display.Image to base64 string using tempfile?

How to display list data from SqlAlchemy Query using fastAPI

How to display an image using RowGroup?

Display Image using Base64 GoLang Template

Using template function for accessing the raw bytes of POD data type and strings

How to display image tag in reactjs using template literal?

How to add multiple image urls into postgres database using fastAPI?

How to display image using django

How to display uploaded image in HTML page using FastAPI & Jinja2?

How to compress image and then upload it to AWS S3 bucket using FastAPI?

How to save an uploaded image to FastAPI using Python Imaging Library (PIL)?

How to iterate over a dictionary in Jinja2 using FastAPI?