用心盘Python:让你迷糊和头痛的base64编码

用心盘Python:让你迷糊和头痛的base64编码Base64是一种用64个字符来表示任意二进制数据的编码方法,常用在于URL,Cookie。经常要将字符串、图片转成base64编码,用于api

欢迎大家来到IT世界,在知识的湖畔探索吧!

Base64是一种用64个字符来表示任意二进制数据的编码方法, 常用在于URL, Cookie。

经常要将字符串、图片转成base64编码,用于api传递参数。

首先导入主角包:

import base64

欢迎大家来到IT世界,在知识的湖畔探索吧!

url转成base64字符

欢迎大家来到IT世界,在知识的湖畔探索吧!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编码

欢迎大家来到IT世界,在知识的湖畔探索吧!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编码

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/35936.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信