I need to convert an image (png) to (webp) file.
After uploading a png file, the webp image has been generated, but the webp file didn’t copy the transparency of a png file, instead it creates a black background.
This is my php code:
$type = wp_check_filetype($file, null);
$ext = $type['ext'];
if ($ext === 'png') {
$im = imagecreatefrompng($file);
imagepalettetotruecolor($im);
$webp = imagewebp($im, str_replace('png', 'webp', $file));
}
imagedestroy($im);
The version of PHP is 5.6
4
Answers
You may have to enable the alpha channel and save it. Maybe try this:
Tested on 7.3.0 — works.
DISCLAIMER: May only work on later or some PHP versions.
Only tested on 5.6.15 (didn’t work, black background) and 7.3.0 (worked, transparent background).
Here’s the code:
Edit 1. *** PROOF
The PHP GD library relies on the libgd library.
Link:
https://github.com/libgd/libgd
Relevant code on saves (file: gd_webp.c), Excerpt showing respect of Alpha channel when present:
In regards to
static int _gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
The PHP code I presented relies on the fact that alpha is indeed respected in the GD library and as such works if tested in later PHP version than you are using, specifically I tested in 7.3.0 but may work in early releases after your version.
just add :
between $im = imagecreatefrompng($file); and imagewebp(..
put the image somewhere like:
and you should see your webp in the proper way
There is no need to copy the source image, if the output format supports full alpha transparency. Instead, it is sufficient to tell GD to preserve the alpha channel when saving: