Python 3.x Python3-Base64编码
我有一些图像,我需要使用JSON提供给服务器。我决定使用Base64作为编码系统。 在Python 2中,我可以简单地使用:Python 3.x Python3-Base64编码,python-3.x,encoding,base64,Python 3.x,Encoding,Base64,我有一些图像,我需要使用JSON提供给服务器。我决定使用Base64作为编码系统。 在Python 2中,我可以简单地使用: with open(path, "rb") as imageFile: img_file = imageFile.read() img_string = base64.b64encode(img_file) 但是在Python3中,它不再工作了。 在Python 3中,我需要做哪些更改才能使其正常工作?我遵循了这个解决方案,它似乎适合我。因此,当您以二进
with open(path, "rb") as imageFile:
img_file = imageFile.read()
img_string = base64.b64encode(img_file)
但是在Python3中,它不再工作了。
在Python 3中,我需要做哪些更改才能使其正常工作?我遵循了这个解决方案,它似乎适合我。因此,当您以二进制格式读取图像时,请将其转换为字符串,然后使用base64对字符串进行编码。下面的解决方案来自上面的链接。这是测试的结果
最后,我发现了一个在Python 3.7上运行的代码:
# Get the image
image = open(path, 'rb')
image_read = image_read()
# Get the Byte-Version of the image
image_64_encode = base64.b64encode(image_read)
# Convert it to a readable utf-8 code (a String)
image_encoded = image_64_encode.decode('utf-8')
return image_encoded
尝试了几次,但3.7版不起作用
base64.encodestring
已被弃用,因为Python 3.1.base64.standard_b64encode(content)是做同样事情的另一种方法。我用这种方法对图像进行编码,检查代码。请检查链接。
# Get the image
image = open(path, 'rb')
image_read = image_read()
# Get the Byte-Version of the image
image_64_encode = base64.b64encode(image_read)
# Convert it to a readable utf-8 code (a String)
image_encoded = image_64_encode.decode('utf-8')
return image_encoded