Cant really put my finger on what you are doing wrong, but the code seems to be more complex then it has to be.

Instead of doing the read operations, let base64 module handle it for you

import base64
with open('noaa19-161015.png', 'rb') as fp, open('test.b64', 'w') as fp2:
    base64.encode(fp, fp2)

with open('test.b64', 'rb') as fp, open('test.png', 'wb') as fp2:
    base64.decode(fp, fp2)

Also noticed that you are trying to encode a already encoded string look at the row base64.b64encode(string)

Answer from David Bern on Stack Overflow
🌐
C# Corner
c-sharpcorner.com › article › converting-image-to-base64-in-python
Converting Image To Base64 In Python
March 16, 2023 - In this article, we have learned how to convert an image to base64 format in Python using the Pillow and base64 modules. Encoding an image in base64 format can transfer it over the internet or store it in a text file.
Discussions

python - Encoding an image file with base64 - Stack Overflow
I want to encode an image into a string using the base64 module. I've ran into a problem though. How do I specify the image I want to be encoded? I tried using the directory to the image, but that ... More on stackoverflow.com
🌐 stackoverflow.com
How to decode base64 text file into .png
f.write(data) Don't you mean f.write(decoded) ? More on reddit.com
🌐 r/learnpython
7
1
November 25, 2019
python - How do you base-64 encode a PNG image for use in a data-uri in a CSS file? - Stack Overflow
I want to base-64 encode a PNG file, to include it in a data:url in my stylesheet. How can I do that? I’m on a Mac, so something on the Unix command line would work great. A Python-based solution would also be grand. ... Paul D. WaitePaul D. Waite ... Paul D. WaitePaul D. Waite · 99.4k5757 gold badges204204 silver badges274274 bronze badges ... import base64 ... More on stackoverflow.com
🌐 stackoverflow.com
Encode png bytes to base64
Hello! I`m trying to get png bytes from plotly and i use *py.image.get({}) After that Im trying to encode bytes like “data:image/png;base64,” + str(base64.b64encode(img)) an this doesnt work. I`ve tried urllib.parse.quote_from_bytes(img) but this doesnt work too. More on community.plotly.com
🌐 community.plotly.com
2
0
June 5, 2018
🌐
CodeSpeedy
codespeedy.com › home › convert image to base64 string in python
Convert Image to Base64 String in Python - CodeSpeedy
September 19, 2023 - Then we read the image file and encoded it with the following line: base64.b64encode(img_file.read()) – b64encode() is a method to encode the data into base64
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-image-to-string-and-vice-versa
Python - Convert Image to String and vice-versa - GeeksforGeeks
July 23, 2025 - To convert an image to a string in Python, we can turn the image into a special text format called base64. This allows us to store or send the image as text which is easier to handle in some situations.
🌐
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 - Alternatively, you can convert images to Base64 directly in Python with the Base64 package included in the Python Standard Library.
🌐
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 - Converting an image to Base64 is straightforward in Python, and you don’t need any external libraries because Python provides everything through its built-in base64 module.
🌐
Aspose
blog.aspose.com › aspose.blogs › convert image to base64 in python
Image to Base64 in Python | PNG to Base64 | JPG to Base64
September 13, 2024 - Learn how to convert an image to Base64 in Python using Aspose.SVG API. Explore a free online tool to seamlessly convert PNG or JPG images to Base64.
🌐
Bobby Hadz
bobbyhadz.com › blog › convert-image-to-base64-string-in-python
Convert an Image to Base64 String and vice versa in Python | bobbyhadz
April 11, 2024 - Copied!from io import BytesIO import ... house.webp image in rb (read binary) mode. The base64.b64encode() method is used to encode the bytes-like image object using Base64. If you need to convert the bytes to a string, use the ...
Find elsewhere
🌐
Moonbooks
en.moonbooks.org › Articles › How-to-convert-an-image-png-jpg-etc-to-base64-string-using-python-
How to convert an image (png, jpg, etc) to base64 string using python ?
import base64 with open("img.png", "rb") as img_file: encoded_string = base64.b64encode(img_file.read()) print(encoded_string) ... Earth observation scientist and developer, I explore satellite data, fire detection, and environmental analytics using Python and machine learning.
🌐
Aspose
kb.aspose.com › svg › python › convert-image-to-base64-in-python
Convert Image to Base64 in Python
August 11, 2025 - This short piece of code demonstrates how to convert JPG to Base64 in Python. Supply the image path to the input and use the ToBase64String() method to perform the encoding. Finally, the output string can be written into an SVG file format.
🌐
Base64.Guru
base64.guru › home › base64 converter › base64 encode › image
PNG to Base64 | Image | Base64 Encode | Base64 Converter | Base64
The PNG to Base64 converter is identical to Image to Base64, with the only difference that it forces the mime type to be “image/png” (even if the uploaded file has a different content type or it cannot be detected). Please note that the PNG to Base64 encoder accepts any images types with a size of up to 50 MB.
🌐
Reddit
reddit.com › r/learnpython › how to decode base64 text file into .png
r/learnpython on Reddit: How to decode base64 text file into .png
November 25, 2019 -

Data in the text file is base64 png image. I am trying to decode data file and save to data.png . PyCharm is not showing error in code but when i tried to open image it says: the file "something.png" could not be opened. It may be damaged or use a file format that preview doesn't recognize.

Please advise.

ovo.txt: iw0KGgoVBORAAAANSUhEUgAAADwAAAAeCAIAAAD/+uoYAAAAO0lEQVR4nO3OwQ0AEAAAMey/Mzt4VCTXCTr3+M96HbhRWimtlFZKK6WV0kpppbRSWimtlFZKK6WV0soBsq4BO2SEu+wAAAAASUVORK5CYII=

Code:

import base64
data = open("ovo.txt", "r").read()
decoded = base64.b64decode(data)
filename = "something.png"
with open("something.png", "w") as f:
    f.write(data)
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=='
🌐
Base64
base64.sh › home › all tools › png to base64
PNG to Base64 Converter | Encode PNG Image to Base64 String Online
A: JavaScript (browser): const uri = await new Promise(r => { const f = new FileReader(); f.onload = () => r(f.result); f.readAsDataURL(pngFile); }); Node.js: fs.readFileSync('logo.png').toString('base64') Python: import base64; base64.b64encode(open('logo.png','rb').read()).decode() PHP: base64_encode(file_get_contents('logo.png')) Go: base64.StdEncoding.EncodeToString(pngBytes) Ruby: Base64.strict_encode64(File.read('logo.png'))
🌐
PixelPanda
pixelpanda.ai › home › free tools › image to base64
Image to Base64 — Convert Any Image to Base64 Online Free | PixelPanda
For batch conversion, use a script: in Python, loop through files with base64.b64encode(). In Bash: for f in *.png; do base64 "$f" > "$f.b64"; done. For a quick web approach, convert each image here one at a time.
🌐
Medium
annacsmedeiros.medium.com › efficient-image-processing-in-python-a-straightforward-guide-to-base64-and-numpy-conversions-e9e3aac13312
Efficient Image Processing in Python: A Straightforward Guide to Base64 and Numpy Conversions | by Anna C S Medeiros | Medium
March 30, 2024 - import cv2 import base64 encode_params = [int(cv2.IMWRITE_PNG_COMPRESSION), 9] _, buffer = cv2.imencode('.png', my_opencv_image, encode_params) b64_bytearr = base64.b64encode(buffer).decode("utf-8") b64 = str(b64_bytearr, 'utf-8')
🌐
Plotly
community.plotly.com › 📊 plotly python
Encode png bytes to base64 - 📊 Plotly Python - Plotly Community Forum
June 5, 2018 - Hello! I`m trying to get png bytes from plotly and i use *py.image.get({}) After that Im trying to encode bytes like “data:image/png;base64,” + str(base64.b64encode(img)) an this doesnt work. I`ve tried urllib.parse.quote_from_bytes(img) but this doesnt work too.
🌐
Medium
medium.com › @ajeet214 › retrieve-your-image-from-base64-format-9c23014624b7
Retrieve your image from base64 format | by Ajeet Verma | Python in Plain English
September 28, 2025 - Usually, the images are placed in the common format such as JPEG, PNG, TIFF, GIF, etc. Well, this weird-looking humungous text is the base64 encoding format of the image file, and we are now going to convert this to the real image with the help of the base64 in-built library in Python programming language.