Как автоматически создавать изображения .webp из существующих на сайте файлов .jpg / png, (конвертировать формат изображения .htacces в webp) - PullRequest
0 голосов
/ 23 апреля 2020

.htaccess файл:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^webp/(.*)\.webp?$ webp_generator.php?file=$1 [QSA]

webp_generator. php:

<?php
// get an absolute path
$settings_document_root = dirname(__FILE__);
$file = trim(strip_tags($_GET['file']));
// exit if ORIGINAL file not found
if(!is_file($file)){

  // include("404.php");
  echo "original file not found";
  exit;
}
// detect if file is png/jpg/gif, for gif we use gif2webp command
$file_extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
// mkdir -p to create parent directories if needed (e.g a full path of sub directories)
exec("mkdir -p ".escapeshellarg("webp/".dirname($file)));

// convert png, jpg
if($file_extension=="png" or $file_extension=="jpg"){
  exec("cwebp -q 80 ".escapeshellarg($settings_document_root."/".$file)." -o ".escapeshellarg($settings_document_root."/webp/".$file.".webp"));
}
// convert gif
if($file_extension=="gif"){
  exec("gif2webp -q 80 ".escapeshellarg($settings_document_root."/".$file)." -o ".escapeshellarg($settings_document_root."/webp/".$file.".webp"));
}

// show warning if file was not generated properly, you can replace this with a header() redirect to a default image
if(!file_exists($settings_document_root."/webp/".$file.".webp")){
  echo "cannot generate webp file ".escapeshellarg("webp/".$file);
  exit;
}

// maintenance, delete old webp files, then delete empty directories
exec("find webp/ -type f -mtime +30 -delete");
exec("find webp/ -type d -empty -delete");

// continue to showing the generated web file
// the ?time() is there so that it doesn't redirect back to itself on first time when image is generated
// that can cause an infinite loop because it caches file as a redirect back to itself
header("Location: /webp/".$file.".webp?".time());
exit;?>

Как мне организовать работу с Imagick?

cwebp и gif2webp являются не установлен на моем сервере. Я хочу установить тот же скрипт для работы с Imagick

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...