微軟小冰顏值測試PHP最新代碼

<?php

/**
 * 微軟小冰顏值測試
 */
class IceFace
{
    // 顏值測試首頁
    protected $page = 'http://kan.msxiaobing.com/ImageGame/Portal?task=yanzhi';
    // 顏值測試接口
    protected $api = 'http://kan.msxiaobing.com/Api/ImageAnalyze/Process?service=yanzhi';
    // 上傳圖片接口
    protected $fileApi = 'http://kan.msxiaobing.com/Api/Image/UploadBase64';

    // 錯誤信息
    protected $error = '';

    // 保存會話的文件
    protected $cookieFile = '';

    // 原數(shù)據(jù)
    public $srcData = [];
    // 評分
    public $score = 0;
    // 調(diào)侃
    public $ridicule = '';
    // 人臉圖片
    public $imgOfFace = '';
    // 原圖片文件
    public $srcImgPath = '';

    /**
     * 構(gòu)造函數(shù)
     * @param string $file_path 本地或網(wǎng)絡(luò)的文件路徑
     */
    public function __construct($file_path)
    {
        $this->srcImgPath = $file_path;
        // 建立一個零時文件
        $this->cookieFile = tempnam('./temp', 'cookie');
    }

    /**
     * 顏值測試
     * @return boolean 測試是否成功
     */
    public function test()
    {
        $ret = $this->send($this->page);
        if (empty($ret)) {
            return $this->setError('訪問顏值測試主頁失敗');
        }

        $ret = $this->uploadImgage($this->srcImgPath);
        if (!isset($ret->Host) || !isset($ret->Host)) {
            return $this->setError('上傳圖片到微軟服務(wù)器錯誤');
        }

        $data = [
            'MsgId' => str_pad(time(), 13, '0'),
            'CreateTime' => time(),
            'Content[imageUrl]' => $ret->Host . $ret->Url,
        ];
        $headers = [
            'Referer' => $this->page,
            'User-Agent' => 'Python-urllib/2.7',
            'Connection' => 'close',
        ];

        $rsp = $this->send($this->api, $data, 'POST', $headers);
        if (empty($rsp)) {
            return $this->setError('顏值測試失敗');
        }
        $this->srcData = json_decode($rsp, true);
        if (!isset($this->srcData['content'])) {
            return $this->setError('返回的數(shù)據(jù)異常');
        }
        // 解析原始數(shù)據(jù)
        $this->paramSrcData();
    }

    /**
     * 獲取錯誤信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 解析原始數(shù)據(jù)
     */
    private function paramSrcData()
    {
        if (empty($this->srcData)) {
            return;
        }
        preg_match('/[-+]?([0-9]*\.[0-9]+|[0-9]+)/', $this->srcData['content']['text'], $matches);
        if (!empty($matches) && isset($matches[0])) {
            $this->score = $matches[0];
        }
        $this->ridicule = $this->srcData['content']['text'];
        $this->imgOfFace = $this->srcData['content']['imageUrl'];
    }

    /**
     * 設(shè)置錯誤信息
     * @return boolean
     */
    private function setError($message = '')
    {
        $this->error = $message;
        return false;
    }

    /**
     * 上傳圖片
     * @param  string $file_path 本地或網(wǎng)絡(luò)地址
     * @return data|string       響應(yīng)數(shù)據(jù)
     */
    private function uploadImgage($file_path)
    {
        $img_data = $this->getBase64DataByFilePath($file_path);

        $rsp = $this->send($this->fileApi, $img_data, 'post', [], true);
        if (empty($rsp)) {
            return fasle;
        }
        return json_decode($rsp);
    }

    /**
     * 發(fā)出請求
     * @param  string           $url     URL
     * @param  array|string     $request 請求參數(shù)
     * @param  string           $method  請求方法
     * @return string
     */
    private function send($url, $request = null, $method = 'GET', $headers = [], $is_binary = false)
    {
        $ch = curl_init();
        $method = strtoupper($method);
        if ($method == 'GET') {
            if (is_array($request)) {
                $url = $url . '?' . http_build_query($request);
            }
        }
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($is_binary) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
            } else {
                if (is_array($request)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request));
                }
            }
        }

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->paramHeader($headers));
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // cookie文件
        curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);

        $res = curl_exec($ch);
        curl_close($ch);

        return $res;
    }

    /**
     * 解析header
     * @param array $headers
     * @return array 解析后的頭部數(shù)組
     */
    private function paramHeader($headers)
    {
        $arr = [];
        foreach ($headers as $key => $value) {
            $arr[] = $key . ':' . $value;
        }
        return $arr;
    }

    /**
     * 獲取圖片的Base64編碼的數(shù)據(jù)
     * @param  string $file_path 本地或網(wǎng)絡(luò)地址
     * @return string|base64
     */
    private function getBase64DataByFilePath($file_path)
    {
        return base64_encode(file_get_contents($file_path));
    }
}

$o = new IceFace('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527267326820&di=ed1e3eac833f7cee00cce44aca19cbc5&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F7c1ed21b0ef41bd5221ae1d15bda81cb39db3d4d.jpg');
$o->test();

print_r($o->score);
print_r($o->ridicule);
print_r($o->imgOfFace);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容