How To Change PNG To WEBP Using PHP JQuery

PNG to WEBP Using PHP jQuery

February 12, 2024

To convert PNG images to WEBP using PHP and jQuery, this tutorial walks you through creating a web page with an HTML form that uploads images, and then processes them on the server using PHP. WEBP is a highly efficient image format that reduces file sizes without compromising image quality, making it ideal for web applications.

Step 1: Create the HTML Form

We start by creating a simple HTML form that allows users to upload PNG or JPEG images. The form utilizes the enctype="multipart/form-data" attribute, which is essential when uploading files. Additionally, we are using Bootstrap for quick styling.

HTML Code:

	

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Convert PNG to WEBP</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">         <form method="post" id="submitdata" enctype="multipart/form-data">             <label>Upload PNG or JPEG Image</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 and Convert</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: 'upload.php',             data: formdata,             type: 'POST',             contentType: false,             processData: false,             success: function(data) {                 alert("Uploaded and Converted Successfully");
            }         });     }); </script> </body> </html>

This form contains a file input for uploading images and a submit button. The user can select a PNG or JPEG file, which will be sent to the server using an AJAX request. When the form is submitted, jQuery captures the event, prevents the default page reload, and sends the form data (including the image) to upload.php.

Step 2: Handle Image Conversion in PHP (upload.php)

On the server side, the upload.php file is responsible for processing the uploaded file, converting it to the WEBP format, and storing the converted image in the server’s images folder.

Upload.PHP Code

<?php // Database connection $con = mysqli_connect("localhost", "root", "", "test") or die(mysqli_error($con));

$image = $_FILES['product_image']['name']; $file_tmp = $_FILES['product_image']['tmp_name']; $dir = "images/";

// Generate a new name for the uploaded image $newName = time() . ".webp";

// Move the uploaded file to the server if (move_uploaded_file($file_tmp, $dir . $image)) {     $file_type = $_FILES['product_image']['type'];

    // Create a new image resource based on file type (JPEG or PNG)     if ($file_type == 'image/png') {         $img = imagecreatefrompng($dir . $image);     } else {         $img = imagecreatefromjpeg($dir . $image);     }

    // Set quality for the WEBP conversion (1-100)     $quality = 100;

    // Convert the image to WEBP     imagewebp($img, $dir . $newName, $quality);     imagedestroy($img);

    // Remove the original uploaded image     unlink($dir . $image);

    // Save the new WEBP image name in the database     mysqli_query($con, "INSERT INTO images(imagename) VALUES('$newName')");

    echo "success"; } else {     echo "error"; } ?>  

This PHP script does the following:

Start by creating a folder for your project. Inside this folder, create the following files and directories:

1. Connects to the MySQL database using mysqli.

2. Moves the uploaded image to the images directory.

3. Depending on the file type (image/png or image/jpeg), it creates an image object using imagecreatefrompng() or imagecreatefromjpeg().

4. Converts the image to WEBP format using imagewebp(), with a quality parameter set to 100 for high image quality.

5. Deletes the original PNG or JPEG image after the conversion.

6. Inserts the name of the newly converted WEBP image into the database.

Database Schema (images table)

CREATE TABLE images (
  id INT(11) NOT NULL AUTO_INCREMENT,
  imagename VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

The database schema for storing the image names can be created as follows. This table keeps track of the converted image names.

This table contains two columns: id (the primary key) and imagename (to store the names of converted WEBP images).

The MySQL database stores the names of the converted images, making it easier to retrieve them later. To create the database and table, run the following SQL query in your database management system:

Step 3: Setup SQL Database

The MySQL database stores the names of the converted images, making it easier to retrieve them later. To create the database and table, run the following SQL query in your database management system:

CREATE DATABASE test;
USE test;

CREATE TABLE images (
  id INT(11) NOT NULL AUTO_INCREMENT,
  imagename VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

Conclusion

By following this guide, you can successfully create a system that converts PNG and JPEG images to the more efficient WEBP format using PHP and jQuery. This process is extremely useful for web developers looking to optimize images for faster loading times and reduced bandwidth usage, improving overall website performance. Additionally, the stored data in MySQL allows you to manage and retrieve images efficiently.

This example can be further enhanced by adding more functionality, such as resizing the images before conversion or allowing users to download the converted images directly.