Pergunta

Como você codificar uma imagem png em base64 usando o Python no Windows?

iconfile = open("icon.png")
icondata = iconfile.read()
icondata = base64.b64encode(icondata)

A multa obras acima em Linux e OSX, mas no Windows que irá codificar os primeiros caracteres, em seguida, corte curto. Por que isso?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top