File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Base64
2+
3+ ** Base64,简单地讲,就是用 64 个字符来表示二进制数据的方法** 。这 64 个字符包含小写字母 a-z、大写字母 A-Z、数字 0-9 以及符号"+"、"/",其实还有一个 "=" 作为后缀用途,所以实际上有 65 个字符。
4+
5+ 本文主要介绍如何使用 Python 进行 Base64 编码和解码,关于 Base64 编码转换的规则可以参考 [ Base64 笔记] ( http://www.ruanyifeng.com/blog/2008/06/base64.html ) 。
6+
7+ Python 内置了一个用于 Base64 编解码的库:` base64 ` :
8+
9+ - 编码使用 ` base64.b64encode() `
10+ - 解码使用 ` base64.b64decode() `
11+
12+ 下面,我们介绍文本和图片的 Base64 编解码。
13+
14+ # 对文本进行 Base64 编码和解码
15+
16+ ``` python
17+ >> > import base64
18+ >> > str = ' hello world'
19+ >> >
20+ >> > base64_str = base64.b64encode(str ) # 编码
21+ >> > print base64_str
22+ aGVsbG8gd29ybGQ=
23+ >> >
24+ >> > ori_str = base64.b64decode(base64_str) # 解码
25+ >> > print ori_str
26+ hello world
27+ ```
28+
29+ # 对图片进行 Base64 编码和解码
30+
31+ ``` python
32+ def convert_image ():
33+ # 原始图片 ==> base64 编码
34+ with open (' /path/to/alpha.png' , ' r' ) as fin:
35+ image_data = fin.read()
36+ base64_data = base64.b64encode(image_data)
37+
38+ fout = open (' /path/to/base64_content.txt' , ' w' )
39+ fout.write(base64_data)
40+ fout.close()
41+
42+ # base64 编码 ==> 原始图片
43+ with open (' /path/to/base64_content.txt' , ' r' ) as fin:
44+ base64_data = fin.read()
45+ ori_image_data = base64.b64decode(base64_data)
46+
47+ fout = open (' /path/to/beta.png' , ' wb' ):
48+ fout.write(ori_image_data)
49+ fout.close()
50+ ```
51+
52+ # 小结
53+
54+ - Base64 可以将任意二进制数据编码到文本字符串,常用于在 URL、Cookie 和网页中传输少量二进制数据。
55+
56+ # 参考资料
57+
58+ - [ Base64 - 维基百科,自由的百科全书] ( https://zh.wikipedia.org/wiki/Base64 )
59+ - [ Base64笔记 - 阮一峰的网络日志] ( http://www.ruanyifeng.com/blog/2008/06/base64.html )
60+
61+
You can’t perform that action at this time.
0 commit comments