convert image to webp during upload, php upload image and convert to webp, How to convert images to WebP files using PHP

How to convert images to WebP files using PHP

In this article, we shall cover how to convert images be it either png, jpg, or gif files to webp files using PHP. We are going to discuss how you can change the image type during upload to webp such that the image will be less in size and maintain its quality

What is a WebP File

WebP is an image file format that is modern developed by google to reduce the size of the image at the same time maintaining the quality of the image

One of the things a web developer should ensure is that the website page is loading faster and to achieve this the images present must be of small size. To achieve small size images you should consider using .webp file extension

WebP image files support transparency unlike jpeg images meaning webp files can be used to create logos and branding materials

According to statistics, it is noted that WebP image files are 26% smaller in size compared to png and also up to 34% smaller of jpeg when converted

While displaying images in a web browser for webpages, you should consider using webp image files

How to convert images to WebP files using PHP

We know the common image types that are found include the png and jpeg and it’s hard to ask users to upload webp images only which is not common to most of them (this applies when you have a multivendor ecommerce)

Also if you want to improve performance of your website, you should ensure that you convert the images you are uploading to webp

We will use an example where we will show how to upload an image using PHP and jQuery

  • Create a form that will contain the input type file and ensure that the encrypt type is added

<form method="post" id="submitdata"  enctype="multipart/form-data">

            <label>Image to upload</label>

            <input type="file" name="product_image" class="form-control" accept="image/png, image/jpeg" required>

            <button type="submit" class="btn btn-primary btn-sm">Upload</button>

            </form>

  • Ensure that jQuery link is added in the footer

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>

    $("#submitdata").submit(function(e){

     e.preventDefault();

     var formdata=new FormData(this)

    $.ajax({

    url: 'saveimage',

    data: formdata,

    type: 'POST',

    contentType: false,

    processData: false,

    success: function(data) {

        alert("uploaded successfully")

    }

    });

       });

    </script>

The full HTML and jQuery code with ajax is as follows

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Upload Image using Jquery</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

</head>

<body>

    <div style="margin-top:10%" class="row">

        <div class="col-md-3"></div>

        <div class="col-md-6">

            <h3>Upload image using JQuery Example</h3>

            <hr>

            <form method="post" id="submitdata"  enctype="multipart/form-data">

            <label>Image to upload</label>

            <input type="file" name="product_image" class="form-control" accept="image/png, image/jpeg" required>

            <button type="submit" class="btn btn-primary btn-sm">Upload</button>

            </form>

        </div>

        <div class="col-md-3"></div>

    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

    <script>

    $("#submitdata").submit(function(e){

     e.preventDefault();

     var formdata=new FormData(this)

    $.ajax({

    url: 'saveimage',

    data: formdata,

    type: 'POST',

    contentType: false,

    processData: false,

    success: function(data) {

        alert("uploaded successfully")

    }

    });

       });

    </script>

</body>

</html>

In the PHP file that is handling image upload to server and converting to webp file, follows these steps

  • Collect the name of the image as you have defined in the form
  • Define the directory where you want to save the image to
  • Upload the image to the server

<?php

$image = $_FILES['product_image']['name'];

$file_tmp =$_FILES['product_image']['tmp_name'];

//location to save image once uploaded

$dir="images/";

//upload image to server

move_uploaded_file($file_tmp,$dir.$image);

?>

Converting of image to webp file starts after the image is stored to the server

  • Once the upload is successful, we will need to fetch it and convert it to an object, either png, jpg, or gif depending on the type of the image you have uploaded

//to convert png image to png object

$img = imagecreatefrompng($dir . $image);

//to convert jpg image to jpg object

$img = imagecreatefromjpg($dir . $image);

You should only use one type at a time

If you don’t know the type of image that has been uploaded, you can use the if else function and define depending on the image extension

  • Define the quality of the image you want to generate, can be between 1 to 100

//Quality can be a value between 1-100.

 $quality = 100;

  • Create the webp image file

//Create the webp image.

imagewebp($img, $dir . $newName, $quality);

Note the parameters that are used in the imagewebp function,

the $img represents the object that has been created from the image

$dir represents the directory where the webp image will be stored

$newName is the new name of the image after it has been converted to webp

$quality is the quality of the image

At this stage the webp image file will be saved in the directory defined

  • Destroy the image object you had created

imagedestroy($img);

//delete initial uploaded png image

unlink($dir.$image);

  • Finally, you can save the image name in the database as follows

mysqli_query($con,"INSERT INTO images(imagename) VALUES('$newName')");

The full PHP code to upload image to server and convert image to webp file is as follows

<?php

//connection to the database, replace with your own credentials

$con = mysqli_connect("localhost", "database_user", "database_password", "database_name") or die(mysqli_error($con));

$image = $_FILES['product_image']['name'];

$file_tmp =$_FILES['product_image']['tmp_name'];

//location to save image once uploaded

$dir="images/";

 

//create a new image name

$newName=time().".webp";

 

//upload image to server

if(move_uploaded_file($file_tmp,$dir.$image)){

   

    //Create a png object can either be jpg png or gif

$img = imagecreatefrompng($dir . $image);

 

//Quality can be a value between 1-100.

 $quality = 100;

 

 //Create the webp image.

imagewebp($img, $dir . $newName, $quality);

 

imagedestroy($img);

 

//delete initial uploaded png image

unlink($dir.$image);

 

mysqli_query($con,"INSERT INTO images(imagename) VALUES('$newName')");

echo "success";

}else{

    echo "error";

}

 ?>

That is how you upload an image using PHP and jQuery and convert either png, jpg, or gif image files to webp image files using PHP. Hope you have learned something new. Happy coding