Save webp files as png

Hi,

I am trying to save webp files as png to the database. Is there any existing function to that? Your ideas are appreciated.

http://php.net/manual/en/function.imagepng.php

http://php.net/manual/en/function.imagecreatefromwebp.php

Since Yii 1.1 doesn’t include a native WebP conversion function, you’ll need to rely on PHP’s standard image processing.

If your server has Imagick installed, it’s just a couple of lines:

$image = new Imagick('path/to/file.webp');
$image->setImageFormat('png');
$image->writeImage('path/to/file.png');
$image->clear();

For manual or one-off file conversions outside your backend app, this web converter tool handles WebP to PNG locally in the browser so no files get sent to an external server.

You can convert the WebP to PNG before saving it. If you’re using PHP, GD can load the WebP and then save it with Just make sure your server has WebP support enabled.

Yeah, Imagick makes the backend conversion trivial compared to messing around with GD functions, especially if you want to avoid quality loss or dealing with transparency edge cases.

Though dropping an ad for a random browser converter tool in the middle of a backend PHP thread is always a classic necro-post move. If someone is processing uploads for a database in Yii 1.1, they definitely need it handled server-side in the upload controller anyway, not via some local browser widget. Solid code snippet though!

Simple solution

$webp = 'path/to/image.webp';

$image = imagecreatefromwebp($webp);

if ($image !== false) {
    ob_start();

    imagepng($image);
    $pngData = ob_get_clean();

    imagedestroy($image);

    // Save $pngData to database
    $model->image = $pngData;
    $model->save();
}

If your DB column is BLOB/MEDIUMBLOB, this stores the actual PNG binary data.

If you already have WebP binary data

If the WebP image is coming from an upload and you have its contents:

$webpData = file_get_contents($uploadedFile);

$image = imagecreatefromstring($webpData);

if ($image !== false) {
    ob_start();
    imagepng($image);
    $pngData = ob_get_clean();

    imagedestroy($image);

    $model->image = $pngData;
    $model->save();
}

Important

Check whether your PHP GD supports WebP:

var_dump(function_exists('imagecreatefromwebp'));

If it returns:

bool(true)

you’re good.

If you’re on an older PHP/GD version where WebP isn’t supported, you would need ImageMagick or another image library.

Also, if your goal is only to display the WebP image, I would recommend not converting it to PNG. WebP is generally smaller. Store the original WebP and serve it directly unless you specifically need PNG compatibility.