Python中使用base64
1 import base64 2 import requests 3 import json 4 import os.path 5 from io import BytesIO 6 7 # Python3 base64官方API:https://docs.python.org/3/library/base64.html 8 9 ''' 10 操作字符串 11 ''' 12 test_str = 'hello world!' 13 # 编码 14 encode_str = base64.encodebytes(test_str.encode('utf8')) # b'aGVsbG8gd29ybGQh\n' 15 print(encode_str.decode()) # 默认以utf8解码,结果 aGVsbG8gd29ybGQh 16 # 解码 17 decode_str = base64.decodebytes(encode_str) # b'hello world!' 18 print(decode_str.decode()) # 默认以utf8解码,结果 hello world! 19 20 ''' 21 操作本地图片 22 ''' 23 # 编码 24 with open("D:\\redis.png", 'rb') as f: 25 encode_img = base64.b64encode(f.read()) 26 file_ext = os.path.splitext("D:\\redis.png")[1] 27 print('data:image/{};base64,{}'.format(file_ext[1:], encode_img.decode())) 28 f.close() 29 # 解码 30 with open("D:\\redis2.png", 'wb') as f: 31 f.write(base64.b64decode(encode_img)) 32 f.close() 33 34 ''' 35 操作网络图片 36 ''' 37 # 编码 38 response = requests.get("https://login.sina.com.cn/cgi/pin.php?r=24365533&s=0&p=gz-7c16232cd167e7a4a5ed764688cda14f06bf") 39 encode_wimg = base64.b64encode(BytesIO(response.content).read()) 40 print('data:image/png;base64,%s'% encode_wimg.decode()) 41 # 解码 42 with open("D:\\web.png", 'wb') as f: 43 f.write(base64.b64decode(encode_wimg)) 44 f.close() 45 46 ''' 47 操作字典 48 ''' 49 test_dict = {'hello': 'world', 'year': 2019} 50 # 编码 51 encode_dict = base64.encodebytes(json.dumps(test_dict, ensure_ascii=False).encode()) 52 print(encode_dict.decode()) # 结果 eyJoZWxsbyI6ICJ3b3JsZCIsICJ5ZWFyIjogMjAxOX0= 53 # 解码 54 decode_dict = base64.decodebytes(encode_dict) 55 print(decode_dict.decode()) # 结果 {"hello": "world", "year": 2019} 56 57 ''' 58 操作URL 59 ''' 60 test_url = 'https://docs.python.org/3/library/base64.htm?a=~' 61 # 编码 62 encode_url = base64.encodebytes(test_url.encode()) # 普通编码 63 print(encode_url.decode()) # 结果 eyJoZWxsbyI6ICJ3b3JsZCIsICJ5ZWFyIjogMjAxOX0= 64 65 safe_encode_url = base64.urlsafe_b64encode(test_url.encode()) # URL安全编码 66 print(safe_encode_url.decode()) # 结果 aHR0cHM6Ly9kb2NzLnB5dGhvbi5vcmcvMy9saWJyYXJ5L2Jhc2U2NC5odG0_YT1- 67 68 safe_encode_url = base64.b64encode(test_url.encode(),b'-_') # 编码时使用'-' 替换'+' 使用 '_'替换'/' ,效果与前例相同 69 print(safe_encode_url.decode()) # 结果 aHR0cHM6Ly9kb2NzLnB5dGhvbi5vcmcvMy9saWJyYXJ5L2Jhc2U2NC5odG0_YT1-