微信开发1:图片识别之人脸识别

一、微信图片获取

首先要获得用户发过来的图片,微信公众平台支持接收图片,一条图片消息的格式如下:

<xml>
    <ToUserName><![CDATA[gh_13d1a3a7x46a]]></ToUserName>
    <FromUserName><![CDATA[oKaHDjt60aAyPvQmUX3ddyix_zG8]]></FromUserName>
    <CreateTime>1357543196</CreateTime>
    <MsgType><![CDATA[image]]></MsgType>
    <PicUrl><![CDATA[http://mmsns.qpic.cn/mmsns/L4qjYtOibummV7J7pbpWKZTiaRoeicicD151CGsQ5AW761Kmn5Hk83x5lQ/0]]></PicUrl>
    <MsgId>5830603629728080261</MsgId>
</xml>

XML格式讲解

  • ToUserName 消息接收方微信号,一般为公众平台账号微信号
  • FromUserName 消息发送方微信号
  • CreateTime 消息创建时间
  • MsgType 消息类型;图片消息为image
  • PicUrl 图片链接地址
  • MsgId 消息ID号

这里PicUrl就是图片URL

二、发送图片到接口

在微信接口中代码中获取图片方法如下:接收消息类型中分离出图片类型

public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        logger("R ".$postStr);
        //extract post data
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "image":
                    $resultStr = $this->receiveImage($postObj);
                    break;
            }
            logger("T ".$resultStr);
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

而识别接口的调用方法如下

http://api2.sinaapp.com/recognize/picture/?appkey=0020120430&appsecert=fa6095e123cd28fd&reqtype=text&keyword=http://www.doucube.com.img.800cdn.com/Public/Images/wangluodan.jpg

你可以直接提交微信图片URL

http://api2.sinaapp.com/recognize/picture/?appkey=0020120430&appsecert=fa6095e123cd28fd&reqtype=text&keyword=http://mmsns.qpic.cn/mmsns/wFxOIHALicXicQnmicpXRRkp8URWC1QewPwgH2WdeHf8AYkaOUpdMUzYg/0

如果你喜欢整洁一点,可以使用http_build_query生成请求url,以下供参考

<?php
$doucube_params = array('apihost'=>"http://api2.sinaapp.com/",
'callmethod'=>"recognize/picture/?",
'appkey'=>$appkey,
'appsecert'=>$appsecert,
'reqtype'=>$reqtype,
'keyword'=>$picurl;

echo http_build_query($doucube_params);
?>

三、获得识别结果

上面的程序运行后获得的识别结果如下:默认为Unicode编码

这是识别成功时的结果

{
    "errcode": 0,
    "msgtype": "text",
    "text": {
        "content": "察颜~观色~面相~摸骨~ 嘿!有了:\n年龄:约17岁(碧玉年华)\n漂亮指数:68(天生丽质/:circle)"
    }
}

这是失败时的结果,发送非照片格式文件

{
    "errcode": 1,
    "msgtype": "text",
    "text": {
        "content": "八戒你也真调皮呀!我叫你不要乱扔东西,乱扔东西是不对的。"
    }
}

四、程序中实现

发送图片并且获得返回结果的函数如下:

private function receiveImage($object)
    {
        $apicallurl = urlencode("http://api2.sinaapp.com/recognize/picture/?appkey=0020120430&appsecert=fa6095e123cd28fd&reqtype=text&keyword=".$object->PicUrl);
        $pictureJsonInfo = file_get_contents($apicallurl);
        $pictureInfo = json_decode($pictureJsonInfo, true);
        $contentStr = $pictureInfo['text']['content'];
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }

而transmitText就是封装微信文本消息的函数,与官方样例中雷同

, 相关的文章:

暂无评论

写评论