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: http://i.stack.imgur.com/pwZHv.jpg (JPEG)
Some versions of libgd forget to add a zero padding at the end of odd-sized webp files (this bug, as already mentioned).
It can be fixed with PHP. Replace this:
imagewebp($im);
With this:
ob_start();
imagewebp($im);
if (ob_get_length() % 2 == 1) {
echo "\0";
}
ob_end_flush();
Or alternatively, if you want to create a file rather than output the result directly:
imagewebp($im, 'test_img.webp');
if (filesize('test_img.webp') % 2 == 1) {
file_put_contents('test_img.webp', "\0", FILE_APPEND);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With