I am trying to convert bitmap images into a base64 string before inserting it into database as binary blobs. The base64 string needs to be encoded in such a way that their is a new line character after every 76 characters. What is the best pythonic way of doing this?
For Python version 3:
import base64
base64.encodebytes(s)
https://docs.python.org/3/library/base64.html#base64.encodebytes
Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b'\n') inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME).
Example:
>>> print(base64.encodebytes(b'a' * 100).decode())
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==
>>>
For Python version 2:
import base64
base64.encodestring(s)
http://docs.python.org/library/base64.html
Encode the string s, which can contain arbitrary binary data, and return a string containing one or more lines of base64-encoded data. encodestring() returns a string containing one or more lines of base64-encoded data always including an extra trailing newline ('\n').
The docs for version 2 could certainly be written more clearly, but it does what you want.
Example:
>>> print base64.encodestring('a'*100)
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==
>>>
'\n'.join(s[pos:pos+76] for pos in xrange(0, len(s), 76))
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