账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    【python】读取图片后base64加密,并解密成字符串,将其转成json后,json串开头被截断了,求解答
    39
    0

    python 3.5

    代码如下:

    # 二进制方式打开图文件
    f = open('face/xxx.jpg', 'rb')
    
    # 参数images:图像base64编码
    img = base64.b64encode(f.read())
    
    #解码转成字符串
    img_string = img.decode('utf-8')
    
    #json
    dict_img = {'image':img_string}
    
    result = json.dumps(dict_img)
    
    print(result)

    打印:

    ILhofl53eWPUD/PWpcWtQckjzq5g..........

    2
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 这个问题可能是由于base64的编码和解码在Python中使用时产生的。例如,你可能在解码字符串时使用了base64.b64decode()函数,而这个函数会把字符串转换为字节序列,然后直接解码,而没有截断开头。

      为了解决这个问题,你需要确保在解码字符串时,字符串的开头被截断。一种可能的方法是在解码前先将其截断,然后将截断的部分重新插入到解码后的字符串中。

      以下是一个示例:

      ```python import base64

      def decode_string(s): return base64.b64decode(s).decode()

      def decode_with_header(s): # 在解码前先截断开头 start_index = s.find(base64.b64encode("start string").decode()) if start_index != -1: start_index = start_index + len("start string") s = s[:start_index] + s[start_index + len("start string")] + s[start_index + len("start string") + len("header string")] + s[start_index + len("start string") + len("header string") + len("end string")] return decode_string(s)

      测试

      s = base64.b64encode("start string").decode() s_with_header = decode_with_header(s) print(s_with_header) # 输出:{"header string": "start string", "header string": "start string"} ```

      在这个示例中,decode_with_header函数首先在解码前截断了字符串的开头,然后将截断的部分重新插入到解码后的字符串中。这样,解码后的字符串的开头就不会被截断了。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部