You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Original Full-Size AVIF/WEBP Conversion Fails on Palette-Based PNGs When GD is Used #2018
Both imageavif() and imagewebp() functions fail when passed a palette-based image, because GD requires truecolor images for these conversions.
It appears these compression tools convert standard PNGs into palette-based (indexed color) PNGs. Due to this when uploading a palette-based (indexed color) PNG to WordPress media library, the original full-size AVIF/WebP file fails to convert and ends up as a 0-byte file.
However, resized sub-sizes are unaffected. Upon reviewing the GD editor code in WordPress core, I noticed that the _resize() method in WP_Image_Editor_GD always converts the source image to truecolor before any further processing hence, sub-sizes convert without issue.
A potential solution to avoid conversion failure for original uploads is to hook into wp_handle_upload_prefilter and convert palette PNGs to truecolor before they are passed to GD’s conversion functions.
Example code snippet that fixes this issue:
add_filter( 'wp_handle_upload_prefilter', 'convert_palette_png_to_truecolor' );
functionconvert_palette_png_to_truecolor( $file ) {
if ( ! isset( $file['tmp_name'], $file['name'] ) ) {
return$file;
}
$ext = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
if ( 'png' !== $ext ) {
return$file;
}
$editor = wp_get_image_editor( $file['tmp_name'] );
if ( is_wp_error( $editor ) || ! $editorinstanceof WP_Image_Editor_GD ) {
return$file; // Skip conversion if not using GD.
}
$image = imagecreatefrompng( $file['tmp_name'] );
if ( ! $image || imageistruecolor( $image ) ) {
return$file;
}
// Preserve transparency.imagealphablending( $image, false );
imagesavealpha( $image, true );
// Convert the palette to truecolor.imagepalettetotruecolor( $image );
// Overwrite the upload with the new truecolor PNG.imagepng( $image, $file['tmp_name'] );
imagedestroy( $image );
return$file;
}
changed the title [-]AVIF/WEBP Conversion Fails on Palette-Based PNGs When GD is Used[/-][+]Original Full-Size AVIF/WEBP Conversion Fails on Palette-Based PNGs When GD is Used[/+]on May 27, 2025
Activity
b1ink0 commentedon May 26, 2025
A potential solution to avoid conversion failure for original uploads is to hook into
wp_handle_upload_prefilterand convert palette PNGs to truecolor before they are passed to GD’s conversion functions.Example code snippet that fixes this issue:
cc: @adamsilverstein
mukeshpanchal27 commentedon May 27, 2025
Actually, looks like a possible duplicate of #1561
[-]AVIF/WEBP Conversion Fails on Palette-Based PNGs When GD is Used[/-][+]Original Full-Size AVIF/WEBP Conversion Fails on Palette-Based PNGs When GD is Used[/+]