Reputation: 11705
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?
Upvotes: 11
Views: 3443
Reputation: 15295
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.
Upvotes: 9
Reputation: 32458
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.
Upvotes: 26