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-

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM