用心盤Python:讓你迷糊和頭痛的base64編碼

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.
用心盤Python:讓你迷糊和頭痛的base64編碼


分享到:


相關文章: