phpimage-processinggdimage-manipulationphp-gd

Converting webp to jpeg in with PHP GD Library


I'm having some trouble creating a clean looking image transcode from webp to jpeg using PHP's GD library. As a point of reference Here is a jpeg version of the original using Google's demo here: https://developers.google.com/speed/webp/gallery (I'm including this from the jpeg since I don't seem to be able to upload webp to stackoverflow)

enter image description here

First I tried this basic routine:

$image = imagecreatefromwebp('4.webp');
imagejpeg($image, 'converted.jpg', 100);

This kinda works but the result has a yellow background like this: enter image description here

I also tried using this bit of code for resizing images and drawing a white background first:

$image = imagecreatefromwebp('4.webp');
$width = imagesx($image);
$height = imagesy($image);
$new = imagecreatetruecolor($width, $height);
$background = imagecolorallocate($new, 255, 255, 255);
imagefilledrectangle($new, 0, 0, $width, $height, $background);
imagecopyresampled($new, $image, 0, 0, 0, 0, $width, $height, $width, $height);
imagejpeg($new, 'converted.jpg', 100);

This looks even worse and results in lots of strange artifacts:

enter image description here

Before I completely give up on GD can anyone make a suggestion to get this working properly? First and foremost, I'm looking for a solution using GD functions. If it's not possible I'm open to ImageMagick or another library - but I'd like a bit more insight into what's going wrong here and if it can be done correctly without changing tools.


Solution

  • This may be caused by a well-known bug of an older implementation of LibGD in PHP: http://git.php.net/?p=php-src.git;a=commit;h=a31fe58d8005ff47f8f6ad095dcd4fb3a2f0aae9

    https://bugs.php.net/bug.php?id=70102

    From what I can see it was fixed in PHP 7.0.0: https://www.php.net/ChangeLog-7.php (bug 70102)

    The second potential problem is libgd itselt. Before version 2.2.0 they have used libvpx, in 2.2.0 switched to libwebp.

    I have reproduced the error with PHP 5.6.40 and LibGD 2.1.0. Then upgraded LibGD to 2.2.4 and all is working fine.

    I suggest to upgrade to newer ubuntu, but you can also fetch all the required libraries manually from https://packages.ubuntu.com/search?keywords=libgd or by just increasing the version of the system in /etc/apt/sources.list, doing apt-get update and apt-get upgrade libgd-dev libgd (or libgd2 or libgd3 depending on the package name in your system - I am a Debian user, I do not actively follow Ubuntu packages). Most likely it will remove your php-gd lib so be sure to reinstall it too.