在使用BASE64图片类型过程中出现了NULL提示,经分析和解决过程如下。
一、转化图片为BASE64格式,注意图片的base64编码是不包含图片头的,如data:image/jpg;base64,因此用explode去除图片头。
$v1 = 'images/v1.jpg'; $v2 = 'images/v2.jpg'; $img_v1 = explode(',', imgToBase64($v1)); $img_v2 = explode(',', imgToBase64($v2));
二、$bodys接口中的JSON数据格式如下:
$bodys = "{\"image_template\":{\"image\":\"" . $img_v1[1] . "\", \"image_type\":\"BASE64\", \"quality_control\":\"NONE\"}, \"image_target\":{\"image\":\"$img_v2[1]\", \"image_type\":\"BASE64\", \"quality_control\":\"NONE\"} }";
三、在测试过程中出现param[image_template] is null提示:
string(136) "{"error_code":222001,"error_msg":"param[image_template] is null","log_id":2010505101154,"timestamp":1587451915,"cached":0,"result":null}"
按照百度人脸识别文档,知道image_template类型错误,必须是array格式,因此b o d y s 格 式 有 错 误 , 需 要 转 换 bodys格式有错误,需要转换bodys格式有错误,需要转换bodys格式;
四、json中含有不可见字符,json_decode解析出错
for ($i = 0; $i <= 31; ++$i) { $bodys = str_replace(chr($i), "", $bodys); }
五、完整代码:
$url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=' . $b->access_token; $bodys = "{\"image_template\":{\"image\":\"" . $img_v1[1] . "\", \"image_type\":\"BASE64\", \"quality_control\":\"NONE\"}, \"image_target\":{\"image\":\"" . $img_v2[1] . "\", \"image_type\":\"BASE64\", \"quality_control\":\"NONE\"} }"; for ($i = 0; $i <= 31; ++$i) { $bodys = str_replace(chr($i), "", $bodys); } $res = request_post($url, $bodys); var_dump($res);
Done!