0WordPress的标志使用 wordpress 自动生成和提供 avif 图像

I have spent quite a lot of time optim­ising the per­form­ance of this site, and as part of ongo­ing work I mon­it­or new tech­no­lo­gies that could help improve the speed for vis­it­ors. I’ve been track­ing the adop­tion of next-gen­er­a­tion image formats for a while and with sup­port by web browsers now fairly wide­spread it was time to fig­ure out how to make use of these new formats in wordpress.

There are mul­tiple steps required which I have broken down into head­ings below

在 nginx 中启用支持

The first step is to enable your web serv­er (就我而言,nginx) to recog­nise the mime types of the new formats. 为此,您需要编辑可能在 /etc/nginx/mime.types 中找到的 mime.types. I added the fol­low­ing section

/内容违反规则违反规则;
图像/母牛;
图像/heic-sequence heic;
图像/ heif 序列 heifs;
图像/avif avif;
图像/avif-序列审查;
图像 / jxl jxl;

在文件可用时自动提供文件

The next step is to tell nginx to serve files auto­mat­ic­ally whenev­er they exist (and to fall back to older formats where a new format file does­n’t exist)
To do this first edit the main nginx con­fig file (usu­ally /etc/nginx/nginx.conf) and add the fol­low­ing sec­tion inside the http{} sec­tion of the config

映射 $http_accept $img_ext
{
   ~ 图像 / jxl '.jxl';
   ~图像/avif '.avif';
   〜图像/ webp '.webp';
   默认      '';
}

Note that I am only try­ing to serve jxl (JPEG-加大码) 或avif文件, 你可以添加更多选项 (in order of pref­er­ence!) 如果你希望.
下一个, you need to add the fol­low­ing under the serv­er{} sec­tion of the nginx con­fig (which may be in the main con­fig file or may be in a sep­ar­ate con­fig file depend­ing how you’ve set up your nginx con­fig structure)

位置 ~* ^.+.(PNG|JPG|JPEG)$
{
   add_header 变化 接受;
   try_files $uri$img_ext $uri =404;
}

Now nginx will look for image.jpg.jxl and then image.jpg.avif and then image.jpg.webp and finally image.jpg when it is asked for image.jpg by any browsers that sup­port the new­er formats. 接下来我们需要在wordpress中启用它们

在 wordpress 中启用下一代格式

Add the fol­low­ing code to your functions.php (理想情况下,在子主题中执行此操作,以便在更新主题时不会覆盖更改)

/***************************************************\
* 启用 SVG的 支持和其他现代图像格式 *
\***************************************************/
函数 cc_mime_types( $哑剧 )
{
   $哑剧['svg'] = '图像/svg+xml';
   $哑剧['webp'] = '图像/网络';
   $哑剧[“违反”] = "图像 / 不熟练的 ';
   $哑剧['heif'] = '图像/heif';
   $哑剧['十六进制'] = "图像/违反规则序列';
   $哑剧['小牛'] = '图像/heif-序列';
   $哑剧['avif'] = '图像/avif';
   $哑剧['注意'] = '图像/avif 序列';
   $哑剧['jxl'] ='图像/jxl';
   返回 $mimes;
}
的add_filter( '上传_哑剧', 'cc_mime_types' );

Note that I also enabled sup­port for SVG的 同时图像

Now you can actu­ally upload next gen format images and use them dir­ectly in word­press if you want to, but I don’t recom­mend this as many older browsers don’t sup­port them yet — and we’ve already set up nginx to serve them intel­li­gently so we should make use of that. What we want to do is to auto­mat­ic­ally gen­er­ate the new formats when we upload images (there are plu­gins that do this for webp already, but noth­ing that does it for jxl or avif yet).

安装 libheif

This step does require access to the com­mand line of your web host, which is straight-for­ward if you run a VPS, but may not be so simple if you’re on shared host­ing in which case you might need to ask your host for support
Run the fol­low­ing bash com­mands (these are selec­ted for Centos下 8, oth­er dis­tri­bu­tions may be a little different)

dnf -y 安装 --nogpgcheck https://下载1.rpmfusion.org/free/el/rpmfusion-free-release-8.noarch.rpm https://download1.rpmfusion.org/nonfree/el/rpmfusion-nonfree-release-8.noarch.rpm
dnf -y install libheif

在wordpressfunctions.php中添加自定义函数来压缩所有上传的图片 (和他们的缩略图) 转avif格式

As with the earli­er functions.php step I recom­mend adding this in a child theme

/*****************************\
* 将 png 和 jpg 转换为 avif *
\*****************************/
的add_filter( 'wp_generate_attachment_metadata', 'jps_compress_img', 10, 2 );
函数 jps_compress_img( $元数据, $附件 ID )
{
   // get filepath from id
   $filepath= get_attached_file($附件 ID);

   // is the file a png or jpeg
   if(路径信息($文件路径, PATHINFO_EXTENSION)=="JPG" || 路径信息($文件路径, PATHINFO_EXTENSION)=="JPEG" || 路径信息($文件路径, PATHINFO_EXTENSION)=="PNG")
   {
      // 如果是这样的话, run compression of the main file to avif
      shell_exec("heif-enc $filepath -o $filepath.avif -q 50 -一");
      $零件 = preg_split('~/(?=[^/]*$)~', $文件路径);

      // Then run compression of the thumbnails to avif
      $thumbpaths = $metadata['尺寸'];
      的foreach ($thumbpaths as $key => $拇指)
      {
          $拇指路径= $thumb['文件'];
          $拇指全路径= $parts[0] . "/" . $拇指路径;
          shell_exec("heif-enc $thumbfullpath -o $thumbfullpath.avif -q 50 -一");
      }
   }
   // give back what we got
   return $metadata;
}

//dont forget to delete the avifs if the attachments are deleted
function jps_delete_avif($附件 ID)
{
   $all_images= get_intermediate_image_sizes($附件 ID);
   的foreach($all_images 作为 $each_img)
   {
      $each_img_det= wp_get_attachment_image_src($attach_id,$each_img);
      $each_img_path= ABSPATH.'wp-content'.substr($each_img_det[0],链球菌($each_img_det[0],"/上传/")).'.avif';
      shell_exec("rm -f $each_img_path");
   }
}
ADD_ACTION( '删除附件', 'jps_delete_avif' );

At present that is it — all images you upload will be con­ver­ted to avif cop­ies (with the ori­gin­als retained). You can regen­er­ate all of your images to cre­ate the avif files by using a plu­gin. Note — I haven’t yet set up JPEG-XL com­pres­sion as sup­port for it isn’t avail­able in main­stream browsers yet (although it is in prerelease browsers so it is com­ing very soon).

Whilst I’m cov­er­ing next gen formats and optim­isa­tion though I have one final tip — To com­press SVG的 带有 gzip 的图像 (or even bet­ter zop­fli and brotli). To do that requires anoth­er cus­tom function…

奖金: SVG的 压缩

/*************************************************\
* 压缩 SVG的 使用 brotli 和 zopfli 获取更多图像 *
\*************************************************/
的add_filter( 'wp_generate_attachment_metadata', 'jps_compress_vectors', 10, 2 );
函数 jps_compress_vectors( $元数据, $附件 ID )
{
    // get filepath from id
    $filepath= get_attached_file($附件 ID);

    // is the file an svg
    if(路径信息($文件路径, PATHINFO_EXTENSION)=="SVG")
    {
       // 如果是这样的话, run compression of it using zopfli and brotli
       shell_exec("zopfli --gzip $文件路径");
       shell_exec("brotli --best --output=$filepath.br $filepath");
    }

    // give back what we got
    return $metadata;
}

请注意,您需要在 nginx 配置中启用 gzip_static 和 brotli_static.

为新版本自行编译

I found that on Cen­tos the latest ver­sion of heif-enc is 1.7 which has quite a few bugs when cre­at­ing avifs. So I opted to com­pile my own new­er (1.12) 构建并使用它. Doing so was a little com­plic­ated as it required the aom codec as a shared lib­rary. To do so run the fol­low­ing bash com­mands. Make sure to run them as a nor­mal user, 不是 root 用户. Also note some of these com­mands may not be strictly needed, it took me a while to get it work­ing and I just made a note of what worked — I am by no means a linux expert!

dnf install x265 x265-devel svt-av1
export CXXFLAGS="$CXXFLAGS -fPIC"
cd ~

git clone https://aomedia.googlesource.com/aom
mkdir -p aom_build
cd aom_build
cmake ~/aom -DBUILD_SHARED_LIBS=true
make
sudo make install
cp ./libaom.so.3 /usr/bin/local/libaom.so.3

cd ~
export PKG_CONFIG_PATH=~/aom_build/
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/aom_build/
export LD_LIBRARY_PATH

git clone --recurse-submodules --recursive https://github.com/strukturag/libheif.git
cd libheif
./autogen.sh
./configure
make
sudo make install

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/bin/
export LD_LIBRARY_PATH

一旦你这样做了, make sure it works by run­ning php -a and run­ning the fol­low­ing command

shell_exec("/usr/local/bin/heif-enc -A");

You should get a full out­put, 不只是一个 1 线路错误. Assum­ing that works ok you can modi­fy your functions.php so that each of the shell-exec ref­er­ences points to /us­r/­loc­al/bin/heif-enc instead of just heif-enc

/*****************************\
* 将 png 和 jpg 转换为 avif *
\*****************************/
的add_filter( 'wp_generate_attachment_metadata', 'jps_compress_img', 10, 2 );
函数 jps_compress_img( $元数据, $附件 ID )
{
   // get filepath from id
   $filepath= get_attached_file($附件 ID);

   // is the file a png or jpeg
   if(路径信息($文件路径, PATHINFO_EXTENSION)=="JPG" || 路径信息($文件路径, PATHINFO_EXTENSION)=="JPEG" || 路径信息($文件路径, PATHINFO_EXTENSION)=="PNG")
   {
      // 如果是这样的话, run compression of the main file to avif
      shell_exec("/usr/local/bin/heif-enc $filepath -o $filepath.avif -q 50 -一");
      $零件 = preg_split('~/(?=[^/]*$)~', $文件路径);

      // Then run compression of the thumbnails to avif
      $thumbpaths = $metadata['尺寸'];
      的foreach ($thumbpaths as $key => $拇指)
      {
          $拇指路径= $thumb['文件'];
          $拇指全路径= $parts[0] . "/" . $拇指路径;
          shell_exec("/usr/local/bin/heif-enc $thumbfullpath -o $thumbfullpath.avif -q 50 -一");
      }
   }
   // give back what we got
   return $metadata;
}

请通过下面的评论给我们你的想法! 如果您想订阅,请使用菜单上的订阅链接右上方. 您还可以通过使用下面的链接社会分享这与你的朋友. 干杯.

发表评论