Python 图片Buffer保存为JPG图片(基于微信动态生成小程序码流程)

Python 图片Buffer保存为JPG图片

引言
  • 1、我现在的项目,想要通过不同的商城id来进入小程序,这就涉及到了动态生成小程序码。2、然而通过微信小程序接口,动态生成小程序码的时候,返回的是图片的buffer。
核心代码
from PIL import Image
from io import BytesIO 
# 用来生成一个图片实例,其中imgBuffer 为 图片的 buffer
img = Image.open(BytesIO(imgBuffer))
# 把图片保存在一个路径底下
img.save('/home/sku/111.jpg')
开发流程
  1. 文档在这里 ==> 动态生成小程序码
  2. 下面例子是通过不同的shopid来生成,外部调用CreateEntrance函数来执行获取小程序码图片buffer的流程和保存jpg图片的流程。
appid = '小程序的appid'
appsecret = '小程序的appsecret '
token_url = 'https://api.weixin.qq.com/cgi-bin/token'
code_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit'

def GetToken():
    params = {
        'appid': appid,
        'secret': appsecret,
        'grant_type': 'client_credential'
    }
    res = requests.get(url=token_url, params=params)
    result = json.loads(res.content)
    return result['access_token']

def GetCode(token, shopid):
    data = {
        'page': 'pages/index/index',
        'scene': shopid
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE',
        'Content-Type': "application/json;charset=UTF-8"
    }
    res = requests.post(
        url = code_url + '?access_token=' + token ,
        data = json.dumps(data),
        headers = headers
    )    
    return res.content
    
# 外部调用的函数
def CreateEntrance(shopid):
	# 获取token
    token = GetToken()
    # 根据token和shopid获取指定的小程序码图片 buffer
    imgBuffer = GetCode(token, shopid)

    #保存图片
    img = Image.open(BytesIO(imgBuffer))
    imgPath = '/home/sku/'+ shopid +'.jpg'
    img.save(imgPath)
	
  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值