python json文件传输图片

第一步、将图片转为str

image='1.jpg'
print(type(image))
def imageToStr(image):
    with open(image,'rb') as f:
        image_byte=base64.b64encode(f.read())
        print(type(image_byte))
    image_str=image_byte.decode('ascii') #byte类型转换为str
    print(type(image_str))
    return image_str
image1=imageToStr(image)
print(type(image1))

#输出结果
<class 'str'>
<class 'bytes'>
<class 'str'>
<class 'str'>

第二步、存入json数据:

data = {
  "engineeringdata": {
    "date":12,
    "value": "59.3;98.5",
    "image":image1
  }
}

 第三歩、将json中数据取出转化为图片:

def strToImage(str,filename):
    image_str= str.encode('ascii')
    image_byte = base64.b64decode(image_str)
    image_json = open(filename, 'wb')
    image_json.write(image_byte)  #将图片存到当前文件的fileimage文件中
    image_json.close()

file_address = "./fileimage/" + data['engineeringdata']['date'] + r".jpg"
strToImage(data['engineeringdata']['image'],file_address)

猜你喜欢

转载自blog.csdn.net/weixin_38383877/article/details/82262382
今日推荐