代码
<?php
header("Access-Control-Allow-Origin: *");
header("content:application/json;chartset=uft-8");
class ImgToBase64
{
public $url;
public $base64;
function __construct($url)
{
$this->url = $url;
$this->checkUrl() && $this->tobase64();
}
private function checkUrl()
{
$pattern = '/http[s]?:\/\/[\w\d.\/-]+\.(jpg|png|gif)/i';
preg_match($pattern, $this->url, $match);
if (!isset($match[0])) {
$this->showError();
return false;
}
$this->url = $match[0];
return true;
}
private function tobase64()
{
$imageInfo = @getimagesize($this->url);
if (!$imageInfo) {
$this->showError();
return;
}
$base64 = base64_encode(file_get_contents($this->url));
$base64 = chunk_split($base64);
$blob = 'data:' . $imageInfo['mime'] . ';base64,';
$this->base64 = $blob . $base64;
}
private function showError()
{
$this->base64 = false;
}
public function getBase64()
{
return $this->base64;
}
}
$img_url = isset($_GET['url']) ? $_GET['url'] : false;
if (strpos($img_url, 'http') === false) {
$img_url = 'http:' . $img_url;
}
$res = array(
'error' => 1,
'data' => false
);
if (@getimagesize($img_url)) {
$base64 = new ImgToBase64($img_url);
$img_base64 = $base64->getBase64();
(boolean)$img_base64 && $res = array(
'error' => 0,
'data' => $img_base64
);
}
$json = json_encode($res);
exit($json);
?>
在线地址:https://m.qdxin.cn/appc/getbase64.php?url=https://statics.qdxin.cn/uploadfile/2023/0327/20230327083814275.jpg