How to Create WebP Versions of JPEG Images with PHP

WebP is a modern image format developed by Google that offers superior lossless and lossy compression for images on the web. It can reduce the file size of your pictures by up to 25% compared to JPEG and PNG, leading to faster loading times and lower bandwidth usage for your website.

If you want to use WebP images on your website, you can use the following PHP code to create a WebP version of a new JPEG image if the server supports it:

<?php

// Check if the server supports WebP images
if (imagetypes() & IMG_WEBP) {
  // Get the file path of the JPEG image
  $jpeg_image = '/path/to/image.jpg';

  // Create a WebP version of the image
  $webp_image = '/path/to/image.webp';
  imagewebp(imagecreatefromjpeg($jpeg_image), $webp_image, 80);
}

?>

This code first checks if the server supports WebP images using the imagetypes() function. If WebP is supported, it creates a WebP version of the JPEG image using the imagewebp() Process. The imagecreatefromjpeg() process is used to create an image resource from the JPEG image, which is then passed as the first argument to imagewebp() along with the file path of the WebP image and the quality level (in this case, 80).

To use this code, ensure that the GD library is installed and enabled on your server. The GD library is a PHP extension that provides functions for creating and manipulating image files.

In conclusion, using WebP images on your website can help reduce your pictures’ file size and improve your website’s loading times and bandwidth usage. The above PHP code can be used to create a WebP version of a new JPEG image if the server supports it.

Was this guide helpful?
YesNo