1.小程序调用生成二维码成功的时候,返回的是一个二维码图片的二进制文件流。
2.前端接受到图片的二进制的资源,拼接成
'data:' . $mime . ';base64,'base64_encode($wx_result),
直接返回功前端接受,前端再可以cavase绘图。
3.如果需要浏览器可以直接查看返回的二进制流,拼接成
<image src="'data:' . $mime . ';base64,'base64_encode($wx_result)" >,直接浏览器可以查看。
4.以下是代码分析:
/*
* 生成活动分享页二维码*/
public function buildImgIndex()
{
try{
$unionid = post('unionid');
$fileName = $unionid.'.png';
$fileData = WidRead($fileName);
if($fileData){
echo $this->img_uri($fileData);exit;
}else{
$TokenData = getAccessToken();
if($TokenData['code'] == 200){
$accessToken = $TokenData['data']['access_token'];
}else{
echo jsonOut(returnArr(410,'','error'));exit;
}
$page = "pages/activityflower/activityflower";
$scene = "unionid=".$unionid;
$path = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$accessToken;
$parameter = array(
"access_token" => $accessToken,
'scene' => $scene, //绑定该用户的unionid
'page' => $page,
'auto_color'=>false,
'width'=>430
);
$parameter = json_encode($parameter);
$curl = new \Curl\Curl();
$curl->setHeader('content-type','application/json; charset=utf-8');
$curl->setOpt(CURLOPT_SSL_VERIFYPEER,false);
$curl->setOpt(CURLOPT_SSL_VERIFYHOST,false);
$curl->post($path,$parameter);
if($curl->error){
$error_message = $curl->error_message;
$error_code = $curl->error_code;
$response = $curl->response_headers;
$param['response'] = $response;
$param['code'] = $error_code;
$param['msg'] = $error_message;
$param['contents'] = "coin connect error";
$curl->close();
echo jsonOut(returnArr(400,'',''));
}else{
$data = $curl->response; //返回图片文件流
$curl->close();
}
$dataJson = json_decode($data);//如果成功返回文件流 json_decode为null,其他就自带微信的错误返回
if($dataJson == null){
WidWrite($fileName,$data);
echo $this->img_uri($data);exit;
}else{
echo jsonOut(returnArr(400,'',''));exit;
}
}
}catch(\Exception $e){
$res = array("code" => $e->getCode(), 'msg' => $e->getMessage());
echo jsonOut(returnArr(400, $res, 'error'));exit;
}
}
/*
* 二进制转图片image/png
* */
public function img_uri($contents, $mime ="image/png")
{
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}