Skip to content

Commit

Permalink
Set the webp quality as suggested by @adamsilverstein [here](WordPres…
Browse files Browse the repository at this point in the history
…s/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
  • Loading branch information
erikyo committed Jan 3, 2022
1 parent dcd628d commit a760b9a
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions webp-converter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
}
Expand All @@ -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 );
}
Expand All @@ -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 );
}
Expand Down

0 comments on commit a760b9a

Please sign in to comment.