Add generating efficient images

This commit is contained in:
John Alanbrook 2022-11-07 22:07:29 +00:00
parent 962ed1842c
commit c4867a83dd

View file

@ -16,7 +16,7 @@ if (file_exists("site.json")) {
return false;
}
if (preg_match('/\.(?:jpg|png|css|ico|scss|js|ttf|woff|txt)/', $_SERVER["REQUEST_URI"])) {
if (preg_match('/\.(?:jpg|png|webp|css|ico|scss|js|ttf|woff|txt)/', $_SERVER["REQUEST_URI"])) {
return false;
}
@ -138,6 +138,7 @@ die();
function img_src($src, $root = "" ) {
if (empty($root)) $root = $_SERVER['REQUEST_URI'];
if ($root == "/") $root = "";
if ($src[0] != '/') {
$write = "$root/$src";
} else $write = $src;
@ -168,6 +169,51 @@ function page_locked($page) {
return false;
}
function gen_images($src) {
$path = pathinfo($src);
if (in_array($path['extension'], ["jpg", "jpeg"])) {
$pwebp = "$path[dirname]/$path[filename].webp";
$pe = ltrim($src, '/');
$we = ltrim($pwebp, '/');
if (!file_exists($we)) {
exec("convert -quality 80 $pe $we");
}
}
}
function make_img($src, $q=80) {
$p = img_src($src);
gen_images($p);
$path = pathinfo($p);
$pwebp = "$path[dirname]/$path[filename].webp";
echo <<<END
<picture>
<source srcset="$pwebp" type="image/webp" width=100%/>
<source srcset="$p" type="image/jpeg" width=100% />
<img src="$p" width=100% />
</picture>
END;
}
function make_bkgd_img($src, $q=80) {
$p = img_src($src);
gen_images($p);
$path = pathinfo($p);
$pwebp = "$path[dirname]/$path[filename].webp";
$pe = ltrim($pwebp, '/');
$we = ltrim($p, '/');
return "background-image: image-set(url($pe) 1x, url($we) 1x)";
}
?>