Home >Backend Development >PHP Tutorial >Use PHP to turn your girlfriend's photos into cute anime avatars!
在网上看到一篇将女朋友照片转成动漫头像的博文(java实现),emmmmm, 我不会Python, 又不会Java,更重要的是没有女朋友! 所以我决定用万能的PHP
实现将别人女朋友照片转成动漫头像!
首先注册个百度AI
,然后进到人像动漫化开通控制台(好像是前500次免费调用接口)。
到我的控制台创建应用
然后把Api Key
和Serect Key
记下来, 等下需要用来获取AccessToken
获取AccessToken
1.先封装一个curl请求方法
<?php class Curl { public function post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $curl = curl_init();//初始化curl 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_POSTFIELDS, $curlPost); $data = curl_exec($curl);//运行curl if ($error = curl_error($curl)) { die($error); } curl_close($curl); return $data; } }
2.获取AccessToken
require_once 'Curl.php'; class AccessToken { // Api Key private $apiKey= ''; // Secret Key private $secretKey = ''; private $requestToeknUrl = "https://aip.baidubce.com/oauth/2.0/token"; private $accessToken; public function __construct() { // 默认有效时间2592000秒, 可以存到缓存中 // 对返回的数据没做过段判断, 需要的请自行判断处理 $this->accessToken = ($this->requestAccessToken())['access_token']; } public function requestAccessToken(){ $url = $this->requestToeknUrl; $postData['grant_type'] = 'client_credentials'; $postData['client_id'] = $this->apiKey; $postData['client_secret'] = $this->secretKey; $o = ""; foreach ( $postData as $k => $v ) { $o.= "{$k}=" . urlencode( $v ). "&" ; } $postData = trim($o, '&'); $result = (new Curl())->post($url, $postData); return json_decode($result, true); } public function getAccessToken() { return $this->accessToken; } }
通过getAccessToken()
方法获取AccessToken
<?php // require_once 'Curl.php'; require_once 'AccessToken.php'; class Demo { public function index() { // 获取AccessToken $accessToken = (new AccessToken())->getAccessToken()); // 百度AI接口 $url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=' . $accessToken; // 图片路径 $img = file_get_contents('C:\Users\Admin\Desktop\6a56f099861bf4c470e5d24f7017b1a.jpg'); // base64编码的图片, 可以是本地图片或网络上传的, 只要能转成base64编码就可以了 $img = base64_encode($img); $bodys = array( 'image' => $img ); $result = (new Curl())->post($url, $bodys); $result = json_decode($result, true); // data:image/jpg;base64, echo "<img src=\"data:image/jpg;base64,{$result['image']}\" / alt="Use PHP to turn your girlfriend's photos into cute anime avatars!" >"; } } (new Demo())->index();
最后贴上别人的女朋友o(╥﹏╥)o
推荐学习:《PHP视频教程》
The above is the detailed content of Use PHP to turn your girlfriend's photos into cute anime avatars!. For more information, please follow other related articles on the PHP Chinese website!