Python中的base64编码与解码(转载)

一步步慢慢啃书
在练习中遇到base64的代码,所以就具体了解了一下,参考下面的文章:
https://www.cnblogs.com/zanjiahaoge666/p/7242642.html
Base64编码
广泛应用于MIME协议,作为电子邮件的传输编码,编码可逆,后面不足4位的用‘=’补齐,生成的编码是ascii字符
优点:速度快,ascii字符不可直接读取意义
缺点:编码长,易破解,用于非关键信息
Python2中
import base64
s=‘我是字符串’
a=base64.b64encode(s)#编码
b=base64.b64decode(a)#解码
Python3
因为python3.x中字符都为Unicode编码,而b64encode函数的参数为byte类型,所以必须转码
import base64
encodestr=base64.b64encode(‘abcr34r344r’.encode(‘utf-8’))
print(encodestr)
b’YWJjcjM0cjM0NHI=’

结果和我们预想的有点区别,我们只想要获得YWJjcjM0cjM0NHI=,而字符串被b’'包围了。
这时肯定有人说了,用正则取出来就好了。。。别急。。。
b 表示 byte的意思,我们只要再将byte转换回去就好了。。。源码如下
import base64

encodestr = base64.b64encode(‘abcr34r344r’.encode(‘utf-8’))
print(str(encodestr,‘utf-8’))
打印结果为
YWJjcjM0cjM0NHI=
.github.io/flowchart.js/

python3中解码如下:
s=‘我是字符串’
a=base64.b64encode(s.encode(‘utf-8’))#编码
print(a)
b=str(a,‘utf-8’)
print(b)
c=base64.b64decode(b.encode(‘utf-8’))#解码
print(str(c,‘utf-8’))#输出一定要使用这个str()才能还原

python3中对图像进行编码和解码
with open(‘1.jpg’,‘rb’) as f :#以二进制读取图片
data=f.read()
encodestr=base64.b64encode(data)#得到byte编码的数据
print(str(encodestr,‘utf-8’))#重新编码数据
图片解码:
import numpy as np
from io import BytesIO
from PIL import Image

inf=BytesIO(base64.b64decode(encodestr))
image=Image.open(inf)
image=np.asarray(image,dtype=np.uint8)

你可能感兴趣的:(编码,base64,编码)