Python 图片Buffer保存为JPG图片
引言
-
1、我现在的项目,想要通过不同的商城id来进入小程序,这就涉及到了动态生成小程序码。2、然而通过微信小程序接口,动态生成小程序码的时候,返回的是图片的buffer。
核心代码
from PIL import Image
from io import BytesIO
img = Image.open(BytesIO(imgBuffer))
img.save('/home/sku/111.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 = GetToken()
imgBuffer = GetCode(token, shopid)
img = Image.open(BytesIO(imgBuffer))
imgPath = '/home/sku/'+ shopid +'.jpg'
img.save(imgPath)