How do you encode a png image into base64 using python on Windows?
iconfile = open("icon.png")
icondata = iconfile.read()
icondata = base64.b64encode(icondata)
The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?
Open the file in binary mode:
open("icon.png", "rb")
I'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that Windows is interpreting as the end of the file (for legacy reasons) when it is opened in text mode. The other issue is that opening a file in text mode (without the 'b') on Windows will cause line endings to be rewritten, which will generally break binary files where those characters don't actually indicate the end of a line.
To augment the answer from Miles, the first eight bytes in a PNG file are specially designed:
Your code stops at the 1a, as designed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With