Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

convert png to webp in php

// get png in question

$pngimg = imagecreatefrompng($file);

// get dimens of image

$w = imagesx($pngimg);
$h = imagesy($pngimg);;

// create a canvas

$im = imagecreatetruecolor ($w, $h);
imageAlphaBlending($im, false);
imageSaveAlpha($im, true);

// By default, the canvas is black, so make it transparent

$trans = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefilledrectangle($im, 0, 0, $w - 1, $h - 1, $trans);

// copy png to canvas

imagecopy($im, $pngimg, 0, 0, 0, 0, $w, $h);

// lastly, save canvas as a webp

imagewebp($im, str_replace('png', 'webp', $file));

// done

imagedestroy($im);
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #convert #png #webp #php
ADD COMMENT
Topic
Name
3+7 =