From a760b9a615ee21ffda0454f7c5f4e07f2b01ceaf Mon Sep 17 00:00:00 2001 From: Erik Yo Date: Mon, 3 Jan 2022 12:34:37 +0100 Subject: [PATCH] Set the webp quality as suggested by @adamsilverstein [here](https://github.com/WordPress/performance/pull/32#issuecomment-1003632432) To improve the optimization (where possible) I try to use the same compression quality that is used in the jpg so, if this has been compressed with a quality of 50% also the webp will have this quality --- webp-converter.php | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/webp-converter.php b/webp-converter.php index 0832b40..8d245d3 100644 --- a/webp-converter.php +++ b/webp-converter.php @@ -37,10 +37,22 @@ function easylazy_save_webp_copy( $metadata, $attachment_id ) { switch ( $fext ) { case 'jpg': + + $compressionQuality = 82; + + if (extension_loaded('imagick') && class_exists('Imagick')) { + $img = new Imagick( ); + // the quality of a jpg can be compared with the webp compression with a ratio of 102.5 (82/80) + // source: https://www.industrialempathy.com/posts/avif-webp-quality-settings/#quality-settings-for-a-range-of-jpeg-qualities + // getImageCompressionQuality need the exif data to work as intended otherwise will return 82 + $img->readImage( $basedir . '/' . $path . '/' . $filename ); + $compressionQuality = round($img->getImageCompressionQuality() * 1.025); + } + foreach ( $file_collection as $value ) { $image = imagecreatefromjpeg( $basedir . '/' . $path . '/' . $value ); - imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 95 ); + imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', $compressionQuality ); imagedestroy( $image ); } @@ -54,7 +66,7 @@ function easylazy_save_webp_copy( $metadata, $attachment_id ) { imagealphablending( $image, true ); imagesavealpha( $image, true ); - imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 90 ); + imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 82 ); imagedestroy( $image ); } @@ -68,7 +80,7 @@ function easylazy_save_webp_copy( $metadata, $attachment_id ) { imagealphablending( $image, true ); imagesavealpha( $image, true ); - imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 90 ); + imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 82 ); imagedestroy( $image ); }