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

By | May 4, 2020

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.

Moreover, if you plan to show webp image to browser using php, you can read this tutorial.

Understand WebP Image Mime Type and PHP Output it in Browser Directly – PHP Tutorial

Category: PHP

5 thoughts on “A Simple Guide to PHP Convert PNG, JPG, GIF to WebP for Beginners – PHP Tutorial

  1. Deepika Gupta

    not working. i tried using convertImageToWebP(‘pizza-hut.gif’, ‘om.webp’, 80); but its not working.

    Reply
    1. admin Post author

      I have tested convertImageToWebp() with a gif image, it works. What are warnings or errors your php script output?

      Reply

Leave a Reply

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