views:

759

answers:

2

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?

+17  A: 

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.

Miles
+1 because it works.
Brian
he is indeed correct, odd how it works fine without it in linux/osx
directedition
Linus/OSX treat binary and text files the same, while Windows treats carriage return different in text files than it does in binary files. Also, you should click the checkbox next to his answer to mark it as the correct answer.
R. Bemrose
+5  A: 

To augment the answer from Miles, the first eight bytes in a PNG file are specially designed:

  • 89 - the first byte is a check that bit 8 hasn't been stripped
  • "PNG" - let someone read that it's a PNG format
  • 0d 0a - the DOS end-of-line indicator, to check if there was DOS->unix conversion
  • 1a - the DOS end-of-file character, to check that the file was opened in binary mode
  • 0a - unix end-of-line character, to check if there was a unix->DOS conversion

Your code stops at the 1a, as designed.

Andrew Dalke