当前位置:   article > 正文

python 微信小程序通过接口获取到的二维码字符串保存成图片png_python保存 二维码图片

python保存 二维码图片

微信小程序获取到的二维码图片,是一个很长的字符串,不好保存到数据库,前端页面也不好读取。

解决方案:

把图片串保存到本地,然后再去读取本地图片,具体写法如下:

微信小程序获取二维码,python写法:

  1. #获取token
  2. getUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + XCX_APP_ID + '&secret=' + XCX_APP_SECRET
  3. getReq = urllib2.Request(getUrl)
  4. getRes = urllib2.urlopen(getReq)
  5. getResObj = json.loads(getRes.read())
  6. access_token = getResObj["access_token"]
  7. if not access_token:
  8. return False
  9. #scene 是发给小程序接收的参数
  10. textmod = {"scene": scene, "page": XCX_MAIN_PAGE, "width": 900, "auto_color": True, "is_hyaline": False}
  11. textmod = json.dumps(textmod).encode(encoding='utf-8')
  12. header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
  13. "Content-Type": "application/json"}
  14. #获取小程序二维码
  15. url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token
  16. req = urllib2.Request(url=url, data=textmod, headers=header_dict)
  17. res = urllib2.urlopen(req)
  18. res = res.read()
  19. #保存小程序二维码到指定路径
  20. b64str = base64.b64encode(res)
  21. imgFileName = taskId +"_QRcode.png"
  22. pathImg = IMG_UPLOAD_PATH + imgFileName
  23. with open(pathImg, 'wb') as f:
  24. f.write(base64.b64decode(b64str))
  25. return pathImg

通过 https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='  获取到的二维码参数是一段很长的字符串,如下图

可以通过

  1. with open(PATH + 'XX.png','wb') as f:
  2.         f.write(base64.b64decode(b64str))

方法把图片写入指定的路径,就可以打开了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/215471
推荐阅读
相关标签
  

闽ICP备14008679号