小程序通过HTTP协议获取onenet平台上的图片数据并展示

小白学程序,今天跟我学!hhhhh

如果对微信小程序比较熟悉并且不想看过程,可拉至底端直接看最终代码

做了一个物联网项目,想用微信小程序将获取onenet上的图片数据并且展示在小程序端。
首先,http协议api的使用方法和mqtt基本一样,具体看开发文档:onenet api开发文档
但是,如果想获取图片数据, 通过查询数据流的api——“http://api.heclouds.com/devices/device_id/datastreams”只能获取到图片数据的名称,检索等。
返回示例:[“index”]是获取到的图片名称!!!

{
    "errno": 0,
    "data": [
        {
            "unit": "",
            "unit_symbol": "",
            "create_time": null,
            "update_at": "2022-02-28 21:21:51",
            "id": "img",
            "current_value": {
                "index": "900616250_1646054511480_img"
            }
        }
    ],
    "error": "succ"
}

因此,我重新分析了图片通过python上传到onenet云平台的一段代码。
上传图片数据:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#上传图片数据
import requests
url = "http://api.heclouds.com/bindata"
headers = {"api-key": "你的apikey"}
params={"device_id":"你的设备id","datastream_id":"img"}
# device_id是你的设备id
# datastream_id是你的数据流id
files={'file':open('图片文件地址','rb')}
img=files['file'].read()
r=requests.post(url,params=params,data=img,headers=headers)
print(r.status_code)
print(r.content)

下载图片数据:

import requests
from PIL import Image
import matplotlib.pyplot as plt
from io import BytesIO 
url = "http://api.heclouds.com/bindata/900616250_1646050202242_img"
headers = {"api-key": "你的apikey"}
res=requests.get(url,headers=headers).content
bytes_stream=BytesIO(res)
jpg=Image.open(bytes_stream)
plt.figure("Image")
plt.imshow(jpg)
plt.title('image')
plt.show()

最终能绘制出图像。
所以,调用此api接口 “http://api.heclouds.com/bindata/”+[“index”] (index为图片名称)即可获得图片数据信息,但显示为乱码形式。

          wx.request({
            url: 'http://api.heclouds.com/bindata/'+index,
            header:{
              'api-key': '你的apikey'
            },
            method:"GET",
            success: function (res) {
              console.log(res.data)
              });
            }
          })

随后,我在微信公众平台上搜索到了这篇博文:数据格式转化问题
重点是:wx.request里面把responseType设成arraybuffer
在这里插入图片描述
最终代码为:

          wx.request({
            url: 'http://api.heclouds.com/bindata/'+index,
            header:{
              'api-key': '你的apikey'
            },
            method:"GET",
            responseType: 'arraybuffer',
            success: function (res) {
              const base64=wx.arrayBufferToBase64(res.data)        
              that.setData({
                img:'data:image/png;base64,'+base64
              });
            }
          })

wxml:

<image src="{{img}}"></image>
  • 4
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值