I tested it only with base64 image embeded in HTML file but it should be the same.


You have to read image as bytes, encode to base64, convert it to string and then use in

  '<img src="data:image/jpeg;base64,' + data_base64 + '">'

Working example to embed base64 image in HTML file:

import base64

data = open('image.jpg', 'rb').read() # read bytes from file
data_base64 = base64.b64encode(data)  # encode to base64 (bytes)
data_base64 = data_base64.decode()    # convert bytes to string

print(data_base64)

#html = '<html><body><img src="data:image/jpeg;base64,' + data_base64 + '"></body></html>' # embed in html
html = '<img src="data:image/jpeg;base64,' + data_base64 + '">' # embed in html
open('output.html', 'w').write(html)

Example encode and decode base64 image

Answer from furas on Stack Overflow
Discussions

Python 3 image base64 without saving into html img tag - Stack Overflow
I would like to create an image (without save it to the disk), and show it in a browser. As I know I have to create a base64 image, but I don't know how I can make it. Can you help me? Here is my... More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 26, 2018
how to encode image to base64 in python and insert to HTML? - Stack Overflow
Basically what I'm doing is opening an image in python, encoding it to base 64 and then concatenating it to a variable with the HTML IMG tag. When I execute my code I get ยท TypeError: Object of type 'bytes' is not JSON serializable ... with open("TA203_2.jpg", "rb") as imageFile: equipment_image = base64... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Create PNG from base64 encoded html.Img src
So I have an html.Img component in my Dash app that displays an image based on user input. Since some precomputation is required for the initial image to be created, it is saved as a local file temporarily to encode into a base64 string readable by the html.Img component: encoded = ... More on community.plotly.com
๐ŸŒ community.plotly.com
7
0
January 11, 2023
django - Python encode an image in base 64 after a html upload - Stack Overflow
I have an input for images upload in my page. When you click on "send image" the post request is received in my back-end. I don't, and I don't want to, save the image. What I do, from the back, i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 7
107

This should do it in Python:

import base64

binary_fc       = open(filepath, 'rb').read()  # fc aka file_content
base64_utf8_str = base64.b64encode(binary_fc).decode('utf-8')

ext     = filepath.split('.')[-1]
dataurl = f'data:image/{ext};base64,{base64_utf8_str}'

Thanks to @cnst comment, we need the prefix data:image/{ext};base64,

Thanks to @ramazanpolat answer, we need the decode('utf-8')

2 of 7
58

In python3, base64.b64encode returns a bytes instance, so it's necessary to call decode to get a str, if you are working with unicode text.

# Image data from [Wikipedia][1]
>>>image_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x05\x00\x00\x00\x05\x08\x06\x00\x00\x00\x8do&\xe5\x00\x00\x00\x1cIDAT\x08\xd7c\xf8\xff\xff?\xc3\x7f\x06 \x05\xc3 \x12\x84\xd01\xf1\x82X\xcd\x04\x00\x0e\xf55\xcb\xd1\x8e\x0e\x1f\x00\x00\x00\x00IEND\xaeB`\x82'

# String representation of bytes object includes leading "b" and quotes,  
# making the uri invalid.
>>> encoded = base64.b64encode(image_data) # Creates a bytes object
>>> 'data:image/png;base64,{}'.format(encoded)
"data:image/png;base64,b'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='"


# Calling .decode() gets us the right representation
>>> encoded = base64.b64encode(image_data).decode('ascii')
>>> 'data:image/png;base64,{}'.format(encoded)
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

If you are working with bytes directly, you can use the output of base64.b64encode without further decoding.

>>> encoded = base64.b64encode(image_data)
>>> b'data:image/png;base64,' + encoded
b'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
๐ŸŒ
Chrissimpkins
chrissimpkins.github.io โ€บ six-four
Six-Four | base64 Image Encoder and Embedder for HTML, Markdown, CSS, LESS, and SASS Files
Six-Four is a base64 encoder for images that embeds an appropriately formatted, encoded image in HTML, Markdown, CSS, LESS, or SASS files. It will optionally stream the raw encoded image data through the standard output stream for use in other applications. The application automatically detects ...
๐ŸŒ
Base64.Guru
base64.guru โ€บ home โ€บ base64 converter โ€บ base64 encode
Image to Base64 | Base64 Encode | Base64 Converter | Base64
Sometimes you have to send or output an image within a text document (for example, HTML, CSS, JSON, XML), but you cannot do this because binary characters will damage the syntax of the text document. To prevent this, for example, you can encode image to Base64 and embed it using the data URI.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 51564733 โ€บ how-to-encode-image-to-base64-in-python-and-insert-to-html
how to encode image to base64 in python and insert to HTML? - Stack Overflow
Basically what I'm doing is opening an image in python, encoding it to base 64 and then concatenating it to a variable with the HTML IMG tag. When I execute my code I get ยท TypeError: Object of type 'bytes' is not JSON serializable ... with open("TA203_2.jpg", "rb") as imageFile: equipment_image = base64.b64encode(imageFile.read()) logger.debug(str(equipment_image))
๐ŸŒ
DEV Community
dev.to โ€บ snappy_tools โ€บ image-to-base64-the-complete-guide-with-html-css-and-javascript-examples-k9h
Image to Base64: The Complete Guide (with HTML, CSS, and JavaScript examples) - DEV Community
May 18, 2026 - If you've ever needed to embed an image directly into HTML or CSS without a separate file, you've needed Base64 image encoding. This guide covers everything โ€” what it is, when to use it, and how to do it in HTML, CSS, JavaScript, Python, and Node.js.
Find elsewhere
๐ŸŒ
Blogger
ironiccog.blogspot.com โ€บ 2012 โ€บ 08 โ€บ inline-images-in-html-tags-with-python.html
ironic cog: Inline images in HTML tags with Python
August 19, 2012 - If you're familiar with Python then it's straightforward to encode any file using the base64 module, e.g. (for a PNG image): >>> import base64 >>> pngdata = base64.b64encode(open("cog.png",'rb').read()) >>> print "<img src='data:image/png;base64,%s' />" % pngdata And here's an example inlined ...
๐ŸŒ
Plotly
community.plotly.com โ€บ dash python
Create PNG from base64 encoded html.Img src - Dash Python - Plotly Community Forum
January 11, 2023 - Since some precomputation is required for the initial image to be created, it is saved as a local file temporarily to encode into a base64 string readable by the html.Img component: encoded = base64.b64encode(open('output-1.png', 'rb').read()) ...
๐ŸŒ
Tech Coil
techcoil.com โ€บ blog โ€บ how-to-use-python-3-to-convert-your-images-to-base64-encoding
How to use Python 3 to convert your images to Base64 encoding
May 11, 2020 - When you encode your images in Base64, your images can be transferred and saved as text. Although there will be a 37% bloat in space requirements, it can be useful to encode images in Base64. For eโ€ฆ
๐ŸŒ
Cloudinary
cloudinary.com โ€บ home โ€บ image conversion to base64 in python: a comprehensive guide
Image Conversion to Base64 in Python: A Comprehensive Guide | Cloudinary
April 24, 2026 - Implement Cache Busting When embedding Base64 images in CSS or HTML, changes to the image wonโ€™t be detected unless the filename or query string changes. Use cache-busting techniques to ensure updates are reflected. Use Data URI for Small Assets Only Limit the use of Base64 encoding to small assets (under 1 KB) to prevent performance degradation. For larger files, consider traditional loading methods or dynamic on-demand encoding. Automate Conversion for Multiple Images For large projects, create a Python script that automates the conversion of all images in a directory to Base64, saving you from manually handling each file.
๐ŸŒ
sverrirs.blog
blog.sverrirs.com โ€บ 2013 โ€บ 05 โ€บ base64-encoding-image-files-using-python.html
Base64 encoding image files using Python - sverrirs.blog
June 16, 2015 - # Remove any query string elements, basically everything following # a question (?) mark qs_split = image_path.split("?") image_path = qs_split[0] file_name = os.path.join( base_path, image_path) file_name = urllib.unquote(file_name) print "Encoding image: "+file_name encoded_string = "" with open(file_name, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) return encoded_string
๐ŸŒ
Blogger
opentechlabs.blogspot.com โ€บ 2016 โ€บ 09 โ€บ convert-image-to-base64-encoding-python.html
Convert Image to Base64 Encoding - Python | OpenTechLabs
September 21, 2016 - import base64 import requests url = "http://images.freeimages.com/images/previews/118/bicycle-sign-3-1442216.jpg" response = requests.get(url) convertedData = ("data:" + response.headers['Content-Type'] + ";" + "base64," +str(base64.b64encode(response.content).decode("utf-8"))) Now you have the string inside variable called converted data, which holds base64 encoded string for the image mentioned in the url variable. ... POST and GET While creating forms in HTML every one gets at these two methods generally.
๐ŸŒ
Reddit
reddit.com โ€บ r/pythonprojects2 โ€บ how to convert image to base64 in python?
r/PythonProjects2 on Reddit: How to convert image to base64 in Python?
October 27, 2024 - import base64 # Step 1: Import the base64 library # Step 2: Open the image in binary mode with open("your_image.jpg", "rb") as image_file: image_data = image_file.read() # Step 3: Encode the binary data into Base64 format base64_string = base64.b6...
๐ŸŒ
Formspree
formspree.io โ€บ blog โ€บ image-to-base64
How to Convert an Image URL to Base64 | Formspree
August 28, 2024 - To convert image URLs to base64 in Python, you will use the requests library to fetch the image data from a URL. Next, you will read the image data into a bytes object. Then, you will use the base64 library to encode the bytes object into a ...
๐ŸŒ
CodeWords
codewords.ai โ€บ blog โ€บ image-convert-base64
Image convert base64: encode and decode in Python | CodeWords
June 3, 2026 - Base64 encoding converts binary image data to ASCII text, increasing size by ~33% but enabling transport through text-only channels (JSON, XML, email). Python's base64 module handles encoding/decoding in two lines; pair it with Pillow for format ...
๐ŸŒ
PixelPanda
pixelpanda.ai โ€บ home โ€บ free tools โ€บ image to base64
Image to Base64 โ€” Convert Any Image to Base64 Online Free | PixelPanda
Quickest way to check: paste the data URI into your browser's address bar and it'll display the image. In code, use atob() in JavaScript or base64.b64decode() in Python to get the binary data back. ... Yep.
Top answer
1 of 2
1

I'm probably too late to the party here, but I just stumbled across this and it sounds to me like an issue with the file's seek position. If image_lookup() reads the file (or causes the file to be read), it may leave the seek position at the end of the file. Subsequent reads of the file (from that position) therefore return nothing.

This makes sense given that commenting out the image_lookup() call, and making a copy of the file instance prior to making the call, both worked. If it is indeed the case, seeking the file back to the start is all you need to do, which is as simple as: file.seek(0).

This is untested, but should be all you need:

c = Client(cId, sId)
c.get_token()
tags = c.image_lookup(imageUploaded)

# Seek file back to the beginning
imageUploaded.seek(0)

urlImage = base64.b64encode(imageUploaded.read())
2 of 2
0

Ok, as I'm not saving the image, once I send it to the API the object in itself isn't available anymore.

Not sure to understand why I still can print it, I had to make a copy of it:

if form.is_valid():
            imageUploaded = request.FILES['image_file']
            imageCopy = copy.deepcopy(imageUploaded)
            try:
                c = Client(cId, sId)
                c.get_token()
                tags = c.image_lookup(imageUploaded)

                urlImage = base64.b64encode(imageCopy.read())

And now it works perfectly fine!

As asked, here is the code of Image_lookup:

def image_lookup(self, imageUploaded, image_type=None):
        '''POST /v1/imageLookup'''
        param_files = [
            ('input_image', ('image.jpg', imageUploaded, image_type or 'image/png'))
        ]

        return self.post('someAPIurl/imageLookup', files=param_files)