• python图片和字符串的转换


    有个业务,需要将图片压缩转化为64位编码上传到服务端。

    import json,requests,base64
    #网上下载图片素材
    r = requests.get("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1552573900887&di=4e80542ac9bbb801c7f1cf60fe355570&imgtype=0&src=http%3A%2F%2Fimg009.hc360.cn%2Fg1%2FM09%2F67%2F82%2FwKhQL1L26KyEFHl5AAAAAN7_Cqw821.jpg")
    with open('beng.jpg','wb') as f:
        f.write(r.content)
    
    # 图片的二进制字符串
    with open('beng.jpg', 'rb') as f:
        content2 = f.read()
    with open("beng2.jpg", 'wb') as f:
        f.write(content2)
    
    #图片的64位字符串
    with open('beng.jpg','rb') as f:
        content1 =  base64.b64encode(f.read())
    with open('beng1.jpg','wb') as f:
        f.write(base64.b64decode(content1))
    

    然后应用,先将客户端生成的64位字符保存为baseC.txt,再将服务端返回的64位字符串保存为baseS.txt。
    1.先对2组64位字符长度进行比较
    2.分别保存为图片

    import json,base64
    
    #获取客户端的64位字符串
    with open('baseC.txt', 'rb') as f:
        byteC = f.read()
        # print(isinstance(byteC,bytes))
    
    #获取服务端的64位字符串
    with open('baseS.txt','r') as f:
        #获取服务端的图片编码
        strS = json.loads(f.read())['data']
        #去除b'',先转化为byte
        byte1 = str.encode(strS,"ASCII")
        #使用decode去除b''
        strS = bytes.decode(byte1,"utf-8")
        byteS = str.encode(strS, "ASCII")
    
    with open("baseC.jpg","wb") as f:
        f.write(base64.b64decode(byteC))
    
    with open("baseS.jpg","wb") as f:
        f.write(base64.b64decode(byteS))
    

    经过比对,服务端保存的字符串存储图片失败,客户端保存图片无内容,因此先修复客户端,再进行比对

  • 相关阅读:
    linux 中断映射
    undefined reference to `__stack_chk_guard'
    riscv_clocksource
    source insight
    Illegal instruction mret mret指令返回异常
    Linux内核内存分配函数之devm_kmalloc和devm_kzalloc
    设备树 compatible 属性
    miniriscvos 05Preemptive
    enter_supervisor_mode
    Store/AMO access fault
  • 原文地址:https://www.cnblogs.com/csj2018/p/10534051.html
Copyright © 2020-2023  润新知