效果圖:
准備工作
1、注冊百度賬號
2、登錄百度智能雲控制台
3、在產品列表中找到 人工智能->圖像技術
4、點擊創建應用,如下圖:
代碼
1.創建公共方法 common.php 聲明請求的方法和獲取access_token值的方法
<?php
// 請求方法
function request_post($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
// 初始化curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $postUrl); //抓取指定網頁
curl_setopt($curl, CURLOPT_HEADER, 0); //設置header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 要求結果為字符串且輸出到屏幕上
curl_setopt($curl, CURLOPT_POST, 1);// post提交方式
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($curl); // 運行curl
curl_close($curl);
return $data;
}
// 獲取access_token
function access_token(){
$file = __DIR__ .'\access_token';
if(file_exists($file)){
$str=file_get_contents($file);
try{
$arr=json_decode($str,true);
if(is_array($arr)){
$totime=$arr['totime'];
if($totime>time()){
return $arr['access_token'];
exit;
}
}
}catch(Ecception $e){
}
}
$url = 'https://aip.baidubce.com/oauth/2.0/token'; //固定地址
$post_data['grant_type'] = 'client_credentials'; //固定參數
$post_data['client_id'] = '你的 Api Key'; //創建應用的API Key
$post_data['client_secret'] = '你的 Secret Key'; //創建應用的Secret Key
$o = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$res = request_post($url, $post_data);
$arr =json_decode($res,true);
if(isset($arr['access_token']) && isset($arr['expires_in'])){
$data['access_token']=$arr['access_token'];
$data['totime']=time() + $arr['expires_in'] -3600;
file_put_contents($file, json_encode($data));
return $arr['access_token'];
}else{
return false;
}
}
2.圖片上傳及識別
2.1、在項目的根目錄下創建一個upload文件夾,用於存放上傳的圖片
2.2、創建一個index.html文件,用於上傳圖片及數據渲染
- html代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>使用百度 API </title>
<style type="text/css">
.spanstyle {
display: inline-block;
width: 500px;
height: 500px;
position: relative;
}
</style>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
function imageUpload(imgFile) {
console.log(imgFile.files);
var uploadfile = imgFile.files[0] //獲取圖片文件流
var formData = new FormData(); //創建一個FormData對象
formData.append('file', uploadfile);
//將圖片放入FormData對象對象中(由於圖片屬於文件格式,不能直接將文件流直接通過ajax傳遞到后台,需要放入FormData對象中。在傳遞)
$("#loading").css("opacity", 1);
$.ajax({
type: "POST", //POST請求
url: "upload.php", //接收圖片的地址(同目錄下的php文件)
data: formData, //傳遞的數據
dataType: "json", //聲明成功使用json數據類型回調
//如果傳遞的是FormData數據類型,那么下來的三個參數是必須的,否則會報錯
cache: false, //默認是true,但是一般不做緩存
processData: false, //用於對data參數進行序列化處理,這里必須false;如果是true,就會將FormData轉換為String類型
contentType: false, //一些文件上傳http協議的關系,自行百度,如果上傳的有文件,那么只能設置為false
success: function (msg) { //請求成功后的回調函數
console.log(msg)
//預覽上傳的圖片
var filereader = new FileReader();
filereader.onload = function (event) {
var srcpath = event.target.result;
$("#loading").css("opacity", 0);
$("#PreviewImg").attr("src", srcpath);
};
filereader.readAsDataURL(uploadfile);
if (msg.img_base64) {
$('#img_res').attr('src', msg.img_base64);
}
}
});
}
</script>
</head>
<body>
<fieldset>
<input type="file" onchange="imageUpload(this)">
<legend>圖片上傳</legend>
</fieldset>
<div style="margin-top:2%">
<span class="spanstyle" style="vertical-align: top;border: 1px dashed #ccc;background-color: #4ea8ef;color: white;">
<h4 style="padding-left:2%">原圖:</h4>
<img id="PreviewImg" src="default.jpg" style="width:100%;max-height:100%">
<img id="loading" style="width:100px;height:100px;top: 36%;left: 39%;position: absolute;opacity: 0;"
src="loading.gif">
</span>
<span class="spanstyle" style="vertical-align: top;border: 1px dashed #ccc;background-color: #4ea8ef;color: white;">
<h4 style="padding-left:2%">識別結果:</h4>
<img id="img_res" src="" alt="">
</span>
</div>
</body>
</html>
2.3、創建一個upload.php文件,用於接收圖片及調用圖像識別API
<?php
require './common.php';
$token = access_token();
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp); // 獲取圖片文件后綴名
$_FILES["file"]["name"]=time().'.'.$extension;//圖片重命名(以時間戳來命名)
//將圖片文件存在項目根目錄下的upload文件夾下
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
// 人像動漫化
$url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=' . $token;
$img = file_get_contents("upload/" . $_FILES["file"]["name"]);
$img = base64_encode($img);
$bodys = array(
'image' => $img,
// 'type'=>'anime_mask',
// 'mask_id'=>2
);
$res = request_post($url, $bodys);
$res = json_decode($res,true);
$image_file = "upload/" .$_FILES["file"]["name"];
$image_info = getimagesize($image_file);
if($res['image']){
$res['img_base64'] = "data:{$image_info['mime']};base64," .$res['image']; // 返回處理后的圖片base64
}
echo json_encode($res);die();
注:這個案例是直接參照api文檔做的,未使用過下載的sdk