Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64 png in python on Windows

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?

like image 978
directedition Avatar asked Mar 10 '09 19:03

directedition


2 Answers

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.

like image 167
Miles Avatar answered Oct 13 '22 01:10

Miles


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.

like image 29
Andrew Dalke Avatar answered Oct 13 '22 01:10

Andrew Dalke