支持PHP7.3以上,只支持本地,不支持遠(yuǎn)程OSS,升級(jí)可能會(huì)有影響,
1:\extend\function.php 底部增加
if (!function_exists('diy_convertImageToWebP')) {
/**
* 將圖片轉(zhuǎn)換為WebP格式,并更新數(shù)據(jù)庫記錄。
*
* @param int $imageId 圖片ID
* @return string|bool 成功返回新圖片的URL路徑,失敗返回false
*/
function diy_convertImageToWebP($imageId)
{
//必須支持PHP7.3以上
if(version_compare(PHP_VERSION,'7.3.0','<')) return false;
// 如果圖片ID不存在,則直接返回false
if(!$imageId) return false;
// 查詢圖片數(shù)據(jù)
$imageData = db('uploads')->where('img_id', $imageId)->find();
// 如果圖片數(shù)據(jù)不存在,也返回false
if(!$imageData) return false;
// 構(gòu)建圖片的本地路徑
$localPath = ROOT_PATH . $imageData['image_url'];
$localPath = str_replace(['\\', '//'], '/', $localPath); // 規(guī)范化路徑
// 構(gòu)建圖片的URL路徑
$urlPath = $imageData['image_url'];
$urlPath = str_replace(['\\', '//'], '/', $urlPath); // 規(guī)范化路徑
// 構(gòu)建圖片的URL路徑
$title = pathinfo($imageData['title'], PATHINFO_FILENAME) . '.webp';
// 獲取圖片的基本信息
list($width, $height, $fileType) = @getimagesize($localPath);
// 檢查是否能正確獲取圖片信息
if($fileType === false) return false;
// 根據(jù)圖片類型創(chuàng)建圖像資源
switch ($fileType) {
case IMAGETYPE_GIF:
$imageResource = imagecreatefromgif($localPath);
break;
case IMAGETYPE_JPEG:
$imageResource = imagecreatefromjpeg($localPath);
break;
case IMAGETYPE_PNG:
$imageResource = imagecreatefrompng($localPath);
break;
default:
return false; // 不支持的圖片類型
}
// 定義新的文件名和路徑
$newFileName = pathinfo($localPath, PATHINFO_FILENAME) . '.webp';
$newLocalPath = dirname($localPath) . '/' . $newFileName;
$newUrlPath = dirname($urlPath) . '/' . $newFileName;
// 轉(zhuǎn)換圖片為WebP格式并保存到服務(wù)器
imagewebp($imageResource, $newLocalPath, 80); // 第三個(gè)參數(shù)是圖片質(zhì)量(0-100)
imagedestroy($imageResource); // 釋放內(nèi)存中的圖像資源
//獲得新圖的大小
$newFileSize = filesize($newLocalPath);
// 更新數(shù)據(jù)庫中的圖片信息
db('uploads')->where('img_id', $imageId)->update([
'title' => $title,
'image_url' => $newUrlPath,
'filesize' => $newFileSize,
'mime' => 'image/webp'
]);
// 刪除舊的圖片文件
unlink($localPath);
// 返回新圖片的URL路徑
return $newUrlPath;
}
}
2:\application\admin\controller\Ueditor.php
335行
$data['img_id'] = $img_id;
下面增加
//編輯器單個(gè)上傳-新增圖片上傳成webp
$image_webp = diy_convertImageToWebP($img_id);
if($image_webp) $data['url'] = $image_webp;
760行
/*-------------------------保存上傳圖片記錄 end-----------------------*/
下面增加
//上傳圖片列表-上傳-新增圖片上傳成webp
$image_webp = diy_convertImageToWebP($img_id);
if($image_webp) $return_data['url'] = $image_webp;
修改之前請(qǐng)備份!