Skip to content

Commit a760b9a

Browse files
committed
Set the webp quality as suggested by @adamsilverstein [here](WordPress/performance#32 (comment))
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
1 parent dcd628d commit a760b9a

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

‎webp-converter.php‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,22 @@ function easylazy_save_webp_copy( $metadata, $attachment_id ) {
3737

3838
switch ( $fext ) {
3939
case 'jpg':
40+
41+
$compressionQuality = 82;
42+
43+
if (extension_loaded('imagick') && class_exists('Imagick')) {
44+
$img = new Imagick( );
45+
// the quality of a jpg can be compared with the webp compression with a ratio of 102.5 (82/80)
46+
// source: https://www.industrialempathy.com/posts/avif-webp-quality-settings/#quality-settings-for-a-range-of-jpeg-qualities
47+
// getImageCompressionQuality need the exif data to work as intended otherwise will return 82
48+
$img->readImage( $basedir . '/' . $path . '/' . $filename );
49+
$compressionQuality = round($img->getImageCompressionQuality() * 1.025);
50+
}
51+
4052
foreach ( $file_collection as $value ) {
4153
$image = imagecreatefromjpeg( $basedir . '/' . $path . '/' . $value );
4254

43-
imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 95 );
55+
imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', $compressionQuality );
4456

4557
imagedestroy( $image );
4658
}
@@ -54,7 +66,7 @@ function easylazy_save_webp_copy( $metadata, $attachment_id ) {
5466
imagealphablending( $image, true );
5567
imagesavealpha( $image, true );
5668

57-
imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 90 );
69+
imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 82 );
5870

5971
imagedestroy( $image );
6072
}
@@ -68,7 +80,7 @@ function easylazy_save_webp_copy( $metadata, $attachment_id ) {
6880
imagealphablending( $image, true );
6981
imagesavealpha( $image, true );
7082

71-
imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 90 );
83+
imagewebp( $image, $basedir . '/' . $path . '/' . $value . '.webp', 82 );
7284

7385
imagedestroy( $image );
7486
}

0 commit comments

Comments
 (0)