From 858e9ad48e82a5672676a0acbd3e3bc2e0f03f7f Mon Sep 17 00:00:00 2001 From: Roy Orbitson Date: Tue, 29 Aug 2023 15:29:17 +0930 Subject: [PATCH] Do not serve WebP images that are larger than the original The current code assumes the .webp is always smaller, but occasionally it isn't. Optimiser plugins may report this as "already optimised" or similar. --- inc/Addon/WebP/Subscriber.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/inc/Addon/WebP/Subscriber.php b/inc/Addon/WebP/Subscriber.php index 4ff207d5d5..e25a4aa9e7 100644 --- a/inc/Addon/WebP/Subscriber.php +++ b/inc/Addon/WebP/Subscriber.php @@ -435,14 +435,20 @@ private function url_to_webp( $url, $extensions ) { if ( $this->filesystem->exists( $src_path_webp ) ) { // File name: image.jpg => image.webp. - return preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_url['src'] ) . $src_url['query']; + $src_url_webp = preg_replace( '@\.' . $src_url['extension'] . '$@', '.webp', $src_url['src'] ) . $src_url['query']; + } else if ( $this->filesystem->exists( $src_path_webp = $src_path . '.webp' ) ) { + // File name: image.jpg => image.jpg.webp. + $src_url_webp = $src_url['src'] . '.webp' . $src_url['query']; + } else { + // No webp exists + return false; } - if ( $this->filesystem->exists( $src_path . '.webp' ) ) { - // File name: image.jpg => image.jpg.webp. - return $src_url['src'] . '.webp' . $src_url['query']; + if ( $this->filesystem->size( $src_path_webp ) < $this->filesystem->size( $src_path ) ) { + return $src_url_webp; } + // The webp isn't smaller than the original, so don't use it. return false; }