just two lines could solve this problem:
import base64
base64_code = "VER30QHI30JFOIAIO3020085723F" # this is just an example
img_data = base64_code.encode()
content = base64.b64decode(img_data)
with open('/path/to/your/image.jpg', 'wb') as fw:
fw.write(content)
print(content)
then you could check the image bytes.
Answer from dongrixinyu on Stack Overflowjust two lines could solve this problem:
import base64
base64_code = "VER30QHI30JFOIAIO3020085723F" # this is just an example
img_data = base64_code.encode()
content = base64.b64decode(img_data)
with open('/path/to/your/image.jpg', 'wb') as fw:
fw.write(content)
print(content)
then you could check the image bytes.
you can find the following here:
import base64
base64_message = 'UHl0aG9uIGlzIGZ1bg=='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
Source: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/
python - Decode Base64 string to byte array - Stack Overflow
Convert byte[] to base64 and ASCII in Python - Stack Overflow
Why does base64.b64encode() in python3 return a bytes object, not a string object? Isn't converting to string the point?
PDF Response from base64
The simplest approach would be: Array to json to base64:
import json
import base64
data = [0, 1, 0, 0, 83, 116, -10]
dataStr = json.dumps(data)
base64EncodedStr = base64.b64encode(dataStr.encode('utf-8'))
print(base64EncodedStr)
print('decoded', base64.b64decode(base64EncodedStr))
Prints out:
>>> WzAsIDEsIDAsIDAsIDgzLCAxMTYsIC0xMF0=
>>> ('decoded', '[0, 1, 0, 0, 83, 116, -10]') # json.loads here !
... another option could be using bitarray module.
This honestly should be all that you need: https://docs.python.org/3.1/library/base64.html
In this example you can see where they convert bytes to base64 and decode it back to bytes again:
>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'
You may need to first take your array and turn it into a string with join, like this:
>>> my_joined_string_of_bytes = "".join(["my", "cool", "strings", "of", "bytes"])
Let me know if you need anything else. Thanks!
The question is pretty much in the title. I was working on porting some code to Python3 that talks to an old API at work - there is a bunch of base64 encoding and hmac creation, which when going from Python 2 to 3 means being explicit about what is a string and what is a byte array. But the b64encode returning a byte array tripped me up, because it doesn't make sense (unless I'm missing something).
Shouldn't b64encode take bytes and return string, and b64decode take string and return bytes?