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
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-png-image-to-base64-string-exampleexample.html
Python PNG Image to Base64 String Example - ItSolutionstuff.com
October 30, 2023 - # Import base64 Module import base64 # Python Convert Image to Base64 String with open("image.png", "rb") as imageFile: encodedString = base64.b64encode(imageFile.read()) print(encodedString);
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
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. Waite · 99.5k5757 gold badges205205 silver badges276276 bronze badges ... Save this answer. ... Show activity on this post. ... Copyimport base64 ... 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
Encode PNG image in base64 in Python - Stack Overflow
I have some Python code that generates a dynamic image in PNG format. This works correctly, because I can save the bytes to disk and get a valid PNG image. Then I try to encode the bytes in base64 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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.
🌐
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.
🌐
C# Corner
c-sharpcorner.com › article › converting-image-to-base64-in-python
Converting Image To Base64 In Python
March 16, 2023 - Next, we can convert the image to base64 format using Python's "base64" module.
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-convert-image-to-base64-in-pythonexample.html
How to Convert Image to Base64 String in Python? - ItSolutionstuff.com
October 30, 2023 - # Import base64 Module import base64 # Python Convert Image to Base64 String with open("image.png", "rb") as imageFile: encodedString = base64.b64encode(imageFile.read()) print(encodedString);
Find elsewhere
🌐
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.
🌐
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 - We can directly embed Base64-encoded images into HTML code, which improves page loading speed. We can also store Base64-encoded images directly in databases. In this blog post, we will learn how to convert an image to Base64 in Python. ... To convert JPG or PNG images to Base64, we will use Aspose....
🌐
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.
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=='
🌐
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)
🌐
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.
🌐
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'))
🌐
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')
🌐
Crashlaker
crashlaker.github.io › python › 2020 › 08 › 26 › image_encode_decode_base64.html
Image encode/decode base64 - Carlos Aguni Personal Blog
August 26, 2020 - #https://stackoverflow.com/questions/48229318/how-to-convert-image-pil-into-base64-without-saving/48229407 #ty @Taha Mahjoubi def img_to_base64_str(img): buffered = io.BytesIO() img.save(buffered, format="PNG") buffered.seek(0) img_byte = buffered.getvalue() img_str = "data:image/png;base64," + base64.b64encode(img_byte).decode() return img_str def img_from_base64_str(msg): msg = msg.replace("data:image/png;base64,", "") msg = base64.b64decode(msg) buf = io.BytesIO(msg) img = Image.open(buf) return img #https://stackoverflow.com/questions/38061267/matplotlib-graphic-image-to-base64 def plot_ba
🌐
Esri Community
community.esri.com › t5 › python-questions › in-memory-png-to-base64-string › td-p › 307928
in_memory png to base64 string - Esri Community
February 24, 2017 - Does anyone know how to convert an in memory png to a base64 string? My raster is defined as: png = "in_memory\my_png.png" I then try to convert it: import base64 base64_string = str(base64.b64encode(png)) base64_string gets populated as: aW5fbWVtb3J5XG15X3BuZy5wbmc= Which, when decoded is: in_m...