From c4867a83dd9e98e00e8ada2886565ccfa061709d Mon Sep 17 00:00:00 2001 From: John Alanbrook Date: Mon, 7 Nov 2022 22:07:29 +0000 Subject: [PATCH] Add generating efficient images --- router.php | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/router.php b/router.php index defbef3..52e530c 100644 --- a/router.php +++ b/router.php @@ -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; +} + +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)"; +} + ?>