Search code examples
phpimagejpegcorruptwebp

imagewebp (php) creates corrupted webp files


Recently I've been fiddling with the WebP image format. I use php 5.5.12 for this, with the gd library installed (gd 2.1.0 / webp supported). I noticed that for some reason, PHP creates corrupted webp-images. The code I used is the following:

$im= imagecreatefromjpeg("test_img.jpg");
$succes = imagewebp($im, "test_img.webp");
if ($im !== false && $succes == true) {
    echo "Succes.";
}

I fail to grasp why the webp image written to the filesystem by this php script is corrupt. For your convenience, I have attached one of the test images. After processing, its associated webp image is indeed a corrupt image on my system. I'd appreciate your input on this, as I have no idea why this does not work properly.

Image: https://i.sstatic.net/pwZHv.jpg (JPEG)


Solution

  • For those of you running into the same problems as I did, here is a link to an (at this time) open PHP bugtracker that is - to my knowledge - the source of the problem. https://bugs.php.net/bug.php?id=66590

    It is sad indeed that this is still not fixed, but we can solve it rather elegantly ourselves. For each VP8 frame written by imagewebp(), we need to check if the frame length is even. If this is not the case, we append a zero byte to the end of the frame and continue. Updating of the frame length defined in its header is not relevant, since this is already of proper length - the padding necessary was just never properly added to the file itself.