python base64图片互转,解决base64字符串转PIL图片对象报错:binascii.Error: Incorrect padding问题
更新时间:2024年09月14日 12:39:42 作者:Python咕噜
在Base64编码中,若字符串长度不是4的倍数,需在末尾添加等号作为填充,不符合此规则会导致在转换为图片时出现binascii.Error:Incorrectpadding错误,正确的填充确保编码后的字符串可以正确转换成图片,避免转换错误
base64保存成图片可能会出现: binascii.Error: Incorrect padding
原因:
在Base64编码中,字符串的长度应该是4的倍数,如果不是,则需要在末尾添加等号(‘=’)作为填充,以确保长度正确。
如果不是4的倍数,则在转化为图片过程中会出现 binascii.Error: Incorrect padding 的报错
base64保存成图片代码
import base64 import binascii import re def base64_format(base64_str): # 移除Base64字符串的前缀 base64_str = re.sub(r'data:image/.+?;base64,', '', base64_str) # 检查长度并添加必要的填充 4的倍数 if len(base64_str) % 4 != 0: num_padding = 4 - len(base64_str) % 4 base64_str += '=' * num_padding try: # 解码 image_data = base64.b64decode(base64_str) return image_data # 假设你只是想返回解码后的数据 except binascii.Error as e: print(f"Base64解码错误: {e}") return None def base64_to_images(base64_str, image_path): """ 将base64字符串解码为字节,并保存图片 :param base64_str: base64字符串 :param image_path: 保存图片路径 :return: """ image_data = base64_format(base64_str) png = open(image_path, 'wb+') png.write(image_data) png.close() base64_str = 'data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMqaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjUtYzAxNCA3OS4xNTE0ODEsIDIwMTMvMDMvMTMtMTI6MDk6MTUgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk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BUS5vY4R3jjs1oHbt3bkNy5D4i4HuraLVbW1B1WNTzJ5seZrQ8ty1lozhbi46Tt/psQjeXjp3VOjUExVYqIlSSSpJLIJBBHAjiCO0HxUkk92W993WUYjt8tcBBwCuwlA/eBqr5cptZDV0ba/LqUtl9MzQ4re537vK5QpLlpwp4ER9MXpQKa8x5PaMNRG3nx611+YTuwLimJ3eR2kkYvIx1Z2JLE+MnjViAAKDQohNcSta6uJUkl//2Q==' base64_to_images(base64_str, '1.png')
图片转base64
def images_to_base64(image_path): """ 将图片转成base64字节 :param image_path: 图片路径 :return: """ with open(image_path, 'rb') as f: image_data = f.read() base64_str = base64.b64encode(image_data) print(base64_str)
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
OpenCV里的imshow()和Matplotlib.pyplot的imshow()的实现
这篇文章主要介绍了OpenCV里的imshow()和Matplotlib.pyplot的imshow()的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-11-11
最新评论