PHP圖像優(yōu)化函數(shù)
與Next.js和Nuxt.js等前端框架中常用的圖像優(yōu)化組件一樣,我創(chuàng)建了一個PHP函數(shù),通過傳遞圖像路徑返回優(yōu)化的圖像。這可以優(yōu)化從外部存儲、CMS等接收的圖像。
演示
PHP版本是8.1.22。
也使用GD。
第 1 步:創(chuàng)建 API 來調(diào)整圖像大小并將圖像轉(zhuǎn)換為 WebP
// _image.php <?php $url = $_REQUEST["url"]; $size["W"] = $_REQUEST["w"]; $img_data = file_get_contents($url); $base_img = imagecreatefromstring($img_data); list($base_w, $base_h) = getimagesizefromstring($img_data); $zoom = $size["W"] / $base_w; $image = imagecreatetruecolor($size["W"], $base_h * $zoom); imagecopyresampled($image, $base_img, 0, 0, 0, 0, $size["W"], $base_h * $zoom, $base_w, $base_h); header("Content-Type: image/webp"); header("cache-control: max-age=2592000"); imagewebp($image); imagedestroy($base_img); imagedestroy($image);
我們建議限制可以訪問此 API 的來源和引用者,以及限制要優(yōu)化的圖像 URL 的域。文章來源:http://www.zghlxwxcb.cn/article/368.html
步驟:2 創(chuàng)建一個函數(shù)來生成<img>用于顯示優(yōu)化圖像的標簽。
// get_optimized_image.php <?php function get_path($img_path = "", $size = 390) { return "/_image.php?url=$img_path&w=$size " . $size . "w"; }; function get_optimized_image($attributes) { $breakpoint = [390, 768, 1024, 1280, 1920]; // Feel free to adjust the breakpoint values to your preference. $imgs = array_map(function ($val) use ($attributes) { return get_path($attributes["src"], $val); }, $breakpoint); $attributes["srcset"] = implode(", ", $imgs); ?> <img <?php foreach ($attributes as $key => $value) { if ($value) { echo " {$key}=\"{$value}\""; } } ?> /> <?php }; ?>
第 3 步:顯示優(yōu)化后的圖像
// index.php <?php include_once('get_optimized_image.php'); ?> <body> <?php get_optimized_image(["src" => "https://example.com/example.jpg"]) ?> </body>
文章來源地址http://www.zghlxwxcb.cn/article/368.html
到此這篇關(guān)于在 PHP 中創(chuàng)建圖像優(yōu)化函數(shù) | PHP圖片優(yōu)化的文章就介紹到這了,更多相關(guān)內(nèi)容可以在右上角搜索或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!