diff --git a/src/wp-includes/class-wp-image-editor-gd.php b/src/wp-includes/class-wp-image-editor-gd.php index 10eed8178b938..560420fd18aa4 100644 --- a/src/wp-includes/class-wp-image-editor-gd.php +++ b/src/wp-includes/class-wp-image-editor-gd.php @@ -559,6 +559,17 @@ protected function _save( $image, $filename = null, $mime_type = null ) { imageinterlace( $image, apply_filters( 'image_save_progressive', false, $mime_type ) ); } + // Ensure GD can handle WebP/AVIF output of palette based images. + if ( + in_array( $mime_type, array( 'image/webp', 'image/avif' ), true ) && + ! imageistruecolor( $image ) + ) { + // Preserve transparence and prepare for conversion. + imagealphablending( $image, false ); + imagesavealpha( $image, true ); + imagepalettetotruecolor( $image ); + } + if ( 'image/gif' === $mime_type ) { if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) { return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); diff --git a/tests/phpunit/data/images/png-tests/dice-palette.png b/tests/phpunit/data/images/png-tests/dice-palette.png new file mode 100644 index 0000000000000..e269d0996ab1d Binary files /dev/null and b/tests/phpunit/data/images/png-tests/dice-palette.png differ diff --git a/tests/phpunit/tests/image/editorGd.php b/tests/phpunit/tests/image/editorGd.php index 705037836c5bc..fbec47e1654fb 100644 --- a/tests/phpunit/tests/image/editorGd.php +++ b/tests/phpunit/tests/image/editorGd.php @@ -1121,6 +1121,41 @@ public function test_image_non_existent_extension() { $this->assertTrue( $loaded ); } + /** + * Tests that GD can convert a palette image to WebP. + * + * @ticket 63773 + */ + public function test_convert_palette_image_to_webp() { + if ( ! ( imagetypes() & IMG_WEBP ) ) { + $this->markTestSkipped( 'This test requires WEBP support.' ); + } + + $file = DIR_TESTDATA . '/images/png-tests/dice-palette.png'; + + // Use the `image_editor_output_format` filter to set the output to WebP. + add_filter( + 'image_editor_output_format', + function () { + return array( + 'image/png' => 'image/webp', + ); + } + ); + + $gd_image_editor = new WP_Image_Editor_GD( $file ); + + $gd_image_editor->load(); + + $save_to_file = tempnam( get_temp_dir(), '' ) . '.webp'; + + $gd_image_editor->save( $save_to_file ); + + $this->assertFileExists( $save_to_file ); + + unlink( $save_to_file ); + } + /** * Tests that images can be saved to a stream. *