Base64是一种用64个字符来表示任意二进制数据的编码方法, 常用在于URL, Cookie。
经常要将字符串、图片转成base64编码,用于api传递参数。
首先导入主角包:
import base64
url转成base64字符
def url2base64(): """ url 转 base64 :return: """ article_url = 'https://mp.weixin.qq.com/s/Dy1t6532fH8zuc7GiA7HAg' bytesString = article_url.encode(encoding="utf-8") link = base64.b64encode(bytesString).decode() print(link)
得到的结果为:
aHR0cHM6Ly9tcC53ZWl4aW4ucXEuY29tL3MvRHkxdDY1MzJmSDh6dWM3R2lBN0hBZw==
将图片转为base64编码
def img_to_base64(img_path): """ img 转 base64 :param img_path: :return: """ with open(img_path, "rb") as imageFile: img_str = base64.b64encode(imageFile.read()) return img_str.decode('utf-8')
将图片的base64编码转成图片
def base64_to_img(image_str, save_path='demo.jpg'): """ base64 字符串转 image :param image_str: :param save_path: :return: """ with open(save_path, "wb") as fh: fh.write(base64.b64decode(image_str))
字符串和base64之间操作
copyright = "With great power comes great responsibility." # 字符串 转成 bytes bytesString = copyright.encode(encoding="utf-8") print("bytes2Str:", bytesString) # bytes 进行 base64编码 encodestr = base64.b64encode(bytesString) print("bytes2base64b", encodestr) print("bytes2base64s:", encodestr.decode()) # base64 解码 成字符串 decodestr = base64.b64decode(encodestr) print("base64s2str:", decodestr.decode())
结果为:
bytes2Str: b'With great power comes great responsibility.' bytes2base64b b'V2l0aCBncmVhdCBwb3dlciBjb21lcyBncmVhdCByZXNwb25zaWJpbGl0eS4=' bytes2base64s: V2l0aCBncmVhdCBwb3dlciBjb21lcyBncmVhdCByZXNwb25zaWJpbGl0eS4= base64s2str: With great power comes great responsibility.