base64图片解码与编码

import base64
import requests
import json
import os.path
from io import BytesIO
 
# Python3 base64官方API:https://docs.python.org/3/library/base64.html
 
'''
操作字符串
'''
test_str = 'hello world!'
# 编码
encode_str = base64.encodebytes(test_str.encode('utf8'))  # b'aGVsbG8gd29ybGQh\n'
print(encode_str.decode())  # 默认以utf8解码,结果 aGVsbG8gd29ybGQh
# 解码
decode_str = base64.decodebytes(encode_str)  # b'hello world!'
print(decode_str.decode())  # 默认以utf8解码,结果 hello world!
 
'''
操作本地图片
'''
# 编码
with open("D:\\redis.png", 'rb') as f:
    encode_img = base64.b64encode(f.read())
    file_ext = os.path.splitext("D:\\redis.png")[1]
    print('data:image/{};base64,{}'.format(file_ext[1:], encode_img.decode()))
    f.close()
# 解码
with open("D:\\redis2.png", 'wb') as f:
    f.write(base64.b64decode(encode_img))
    f.close()
 
'''
操作网络图片
'''
# 编码
response = requests.get("https://login.sina.com.cn/cgi/pin.php?r=24365533&s=0&p=gz-7c16232cd167e7a4a5ed764688cda14f06bf")
encode_wimg = base64.b64encode(BytesIO(response.content).read())
print('data:image/png;base64,%s'% encode_wimg.decode())
# 解码
with open("D:\\web.png", 'wb') as f:
    f.write(base64.b64decode(encode_wimg))
    f.close()
 
'''
操作字典
'''
test_dict = {'hello': 'world', 'year': 2019}
# 编码
encode_dict = base64.encodebytes(json.dumps(test_dict, ensure_ascii=False).encode())
print(encode_dict.decode())  # 结果 eyJoZWxsbyI6ICJ3b3JsZCIsICJ5ZWFyIjogMjAxOX0=
# 解码
decode_dict = base64.decodebytes(encode_dict)
print(decode_dict.decode())  # 结果 {"hello": "world", "year": 2019}
 
'''
操作URL
'''
test_url = 'https://docs.python.org/3/library/base64.htm?a=~'
# 编码
encode_url = base64.encodebytes(test_url.encode()) # 普通编码
print(encode_url.decode())  # 结果 eyJoZWxsbyI6ICJ3b3JsZCIsICJ5ZWFyIjogMjAxOX0=
 
safe_encode_url = base64.urlsafe_b64encode(test_url.encode()) # URL安全编码
print(safe_encode_url.decode())  # 结果 aHR0cHM6Ly9kb2NzLnB5dGhvbi5vcmcvMy9saWJyYXJ5L2Jhc2U2NC5odG0_YT1-
 
safe_encode_url = base64.b64encode(test_url.encode(),b'-_') # 编码时使用'-' 替换'+' 使用 '_'替换'/' ,效果与前例相同
print(safe_encode_url.decode())  # 结果 aHR0cHM6Ly9kb2NzLnB5dGhvbi5vcmcvMy9saWJyYXJ5L2Jhc2U2NC5odG0_YT1-
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值