A Simple Guide to PHP Convert PNG, JPG to WebP for Beginners – PHP Tutorial

By | August 14, 2019

WebP image is one of best image format used on sites, it is smaller than other image formats, such as jpg and png. In this tutorial, we will introduce how to convert png, jpg to webp image, you can change your website images to webp by our this tutorial.

webp image tutorials and examples

To convert other format images to webp, we shoud use php imagewebp() function:

imagewebp ( resource $image [, mixed $to = NULL [, int $quality = 80 ]] ) : bool

This function can save or ouput a webp image from other types of images.

Here we give a function to convert png to webp.

function convertImageToWebP($source, $destination, $quality=80) {
	$extension = pathinfo($source, PATHINFO_EXTENSION);
	if ($extension == 'jpeg' || $extension == 'jpg') 
		$image = imagecreatefromjpeg($source);
	elseif ($extension == 'gif') 
		$image = imagecreatefromgif($source);
	elseif ($extension == 'png') 
		$image = imagecreatefrompng($source);
	return imagewebp($image, $destination, $quality);
	
}

How does this function work?

Firstly, we get the format of source image by pathinfo().

$extension = pathinfo($source, PATHINFO_EXTENSION);

Create an image by image type

        if ($extension == 'jpeg' || $extension == 'jpg') 
		$image = imagecreatefromjpeg($source);
	elseif ($extension == 'gif') 
		$image = imagecreatefromgif($source);
	elseif ($extension == 'png') 
		$image = imagecreatefrompng($source);

Convert png, jpg to webp image

return imagewebp($image, $destination, $quality);

Then if you have converted webp image successfully, you can delete source image or not.

Category: PHP

One thought on “A Simple Guide to PHP Convert PNG, JPG to WebP for Beginners – PHP Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *