February 3, 2024
Converting JPG images to the WEBP format is a highly efficient process, and it can be implemented using a simple HTML form, JavaScript, PHP, and SQL. In this guide, we'll walk through the steps needed to create a project that allows users to upload JPG images and automatically convert them to WEBP format, storing the converted files on the server. Let's break down each step of the process and the structure of this project.
HTML Form: We'll begin by creating an HTML form that allows users to upload JPG or PNG files. The form will be simple, with a file input field that restricts the file types to images.
AJAX Request (jQuery): After submitting the form, we'll send the image file to the server using AJAX to avoid refreshing the page.
Database (MySQL): We'll create a table in MySQL to store the names of the converted images.
Folder Structure: The images will be saved in a dedicated folder (images/) on the server. We’ll also establish the structure of the PHP and SQL files required for the project.
Start by creating a folder for your project. Inside this folder, create the following files and directories:
index.php: This will be the main file where the HTML form resides.
upload.php: This is the backend PHP file that will handle the file upload and conversion process.
images/: This is the folder where the converted WEBP images will be stored.
We need to store the names of the converted images in a database. Here's the SQL command to create the necessary table in MySQL:
CREATE TABLE `images` ( `id` int(244) NOT NULL, `imagename` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci; ALTER TABLE `images` ADD PRIMARY KEY (`id`); ALTER TABLE `images` MODIFY `id` int(244) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
This table will store the ID and the name of each converted image.
The HTML form will allow users to upload their images. Here's how it looks:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Uploazad 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"> <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: 'upload.php', data: formdata, type: 'POST', contentType: false, processData: false, success: function(data) { alert("uploaded successfully"); }, error: function() { alert("upload failed"); } }); }); </script> </body> </html>
This form will allow the user to upload either JPG or PNG images. The form submits the file using AJAX, preventing the page from reloading and allowing for a smoother user experience. The jQuery code inside the script tags sends the file to upload.php for processing.
This form will allow the user to upload either JPG or PNG images. The form submits the file using AJAX, preventing the page from reloading and allowing for a smoother user experience. The jQuery code inside the script tags sends the file to upload.php for processing.
The PHP backend script will handle the actual conversion of the uploaded image to the WEBP format. Here's how it works:
<?php //connection to the database, replace with your own credentials $con = mysqli_connect("localhost", "root", "", "test") 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 echo $file_type= $_FILES['product_image']['type']; if($file_type == 'image/png') $img = imagecreatefrompng($dir . $image); else $img = imagecreatefromjpeg($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"; } ?>
Database Connection: We first establish a connection to the MySQL database using mysqli_connect.
File Upload: We retrieve the uploaded file's name and temporary location using the $_FILES array. The file is moved to the images/ folder on the server using move_uploaded_file.
Image Creation: Depending on whether the uploaded file is a PNG or JPG, we create an image resource using either imagecreatefrompng or imagecreatefromjpeg.
Conversion to WEBP: We then convert the image to WEBP format using imagewebp, specifying the output path and quality level. After conversion, we delete the original uploaded image using unlink to free up space.
Database Insertion: Finally, we store the name of the converted image in the images table.
Ensure that the images/ folder has the correct permissions to allow files to be uploaded.
To test the application:
Upload a JPG or PNG image using the form.
The image should be converted to WEBP format and saved in the images/ folder.
The converted image's name should be stored in the MySQL database.
By following this guide, you can easily implement a system to convert JPG and PNG images to WEBP format using PHP. The use of AJAX makes the upload process seamless, and the converted images are efficiently stored on the server for future use. This approach can be extended with additional features such as image resizing, more file type support, or improved error handling, depending on your needs.