由於自己腦子比較笨 記錄一下微信頭像連結轉 base64 的方法
如有侵權請聯絡 18210686506 郝
使用到的工具
composer require ixudra/curl
在 App\Http\Responses 建立一個新的檔案 AjaxResp.php
AjaxResp.php
<?php
namespace App\Http\Responses;
class AjaxResp {
public function __construct() {
$params = func_get_args();
foreach( $params as $param )
{
$this->{$param} = null;
}
}
// 將物件轉為 JSON 物件
public function toJson()
{
$json = json_encode($this, JSON_UNESCAPED_UNICODE);
return response()->make($json)->header('Content-Type', 'application/json; charset=UTF-8');
}
public $ret;
public $msg;
}
建立一個的控制器 然後寫入話不多說直接上碼
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use App\Http\Responses\AjaxResp;
use App\Models\WxUser;
use Curl;
use Image;
class WeChatController extends BaseController
{
public function avatarBridge() {
set_time_limit(60);
$resp = new AjaxResp();
$headimgurl = request('headimgurl');
if( !$headimgurl ) {
$resp->ret = 1;
$resp->msg = 'invalid headimgurl url';
return $resp->toJson();
}
// 獲取大圖
$headimgurl = substr($headimgurl, 0, strripos($headimgurl, '/')) . '/0';
$filename = sha1($headimgurl);
$ymd = date('Ymd');
$uploadDir = public_path("/upload/avatar/$ymd");
if( !is_dir($uploadDir) ) {
@mkdir($uploadDir, 0777, true);
}
$fileuri = "/upload/avatar/$ymd/$filename.png";
$filepath = public_path($fileuri);
if( !file_exists($filepath) || filesize($filepath) < 8 ) {
$response = Curl::to($headimgurl)
->withContentType('image/png')
->withHeader('Connection: close')
->download($filepath);
}
if( !file_exists($filepath) ) {
$resp->ret = 3;
$resp->msg = 'headimgurl download error';
return $resp->toJson();
}
// 頭像 base64
$type = pathinfo($filepath, PATHINFO_EXTENSION);
$avatarData = file_get_contents($filepath);
$resp->ret = 0;
$resp->msg = 'success';
$resp->base64 = 'data:image/' . $type . ';base64,' . base64_encode($avatarData);
return $resp->toJson();
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結