[Tut] PHP compress image optimize, resize and upload - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html) +--- Thread: [Tut] PHP compress image optimize, resize and upload (/thread-99195.html) |
[Tut] PHP compress image optimize, resize and upload - xSicKxBot - 04-12-2022 PHP compress image optimize, resize and upload <div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/04/php-compress-image-optimize-resize-and-upload.jpg" width="300" height="301" title="" alt="" /></div><div><div class="modified-on" readability="7.0909090909091"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on April 11th, 2022.</div> <p>Do you have heavy image files in your application? And do you want to optimize them before pushing them into application directory? This PHP compress image code will help you to <a href="https://phppot.com/jquery/jquery-ajax-image-resize-with-aspect-ratio/">optimize images before upload</a>.</p> <p>The compressed images are scaled down from the original by quality and size. This process makes your media library lightweight and optimized.</p> <p>This article uses <strong>PHP GD function</strong>s to implement image compression. It uses the functions imagecreatefromjpeg(), imagejpeg() to resize the images.</p> <p>We are going to see a quick example and a featured example in PHP to achieve this.</p> <h2>Quick Example</h2> <p>It is a two-step process that this example code performs PHP compress image.</p> <ol> <li>Step 1: imagecreatefromjpeg() gets a <a href="https://phppot.com/php/php-resource-data-type/">resource reference</a> of the source image.</li> <li>Step 2: imagejpeg() creates the compressed image and outputs it to the browser.</li> </ol> <div class="post-section-highlight" readability="35"> <pre class="prettyprint"><code class="language-sql"> <?php $sourceFile = 'image.jpg'; $outputFile = 'compressed-image.jpg'; $outputQuality = 60; $imageLayer = imagecreatefromjpeg($sourceFile); imagejpeg($imageLayer, $outputFile, $outputQuality); ?> </code></pre> </div> <p>In the second step, it accepts the source image identifier and the target quality. It also accepts the name of the output file in which the compressed version will be.</p> <p>It has the least possible number of lines shown below.</p> <p>It optimizes the source and <a href="https://phppot.com/php/php-image-resize/">outputs resized images</a> with the specified quality.</p> <p>There are alternative functions under different PHP extensions to implement image compress. The following <a href="https://www.php.net/manual/en/book.imagick.php" target="_blank" rel="noopener">PHP ImageMagick functions</a> are used to do this.</p> <ul> <li>Imagick::setImageCompression</li> <li>Imagick::setImageCompressionQuality</li> </ul> <h2>Example 2: PHP compress image and upload to the database</h2> <p>This example gives more features on PHP compress image compared to the above code. Some of those features are,</p> <ol> <li>Image upload option via HTML form.</li> <li>Handling JPEG, GIF and PNG image sources to optimize.</li> <li><a href="https://phppot.com/jquery/file-size-validation-using-jquery/">Image file validation</a> and proper error reporting.</li> </ol> <p>This will be useful for embedding to an application with these additional handlings.</p> <h3>File structure</h3> <p>This screenshot shows the file structure of a simple PHP compress image example. It contains structured files and is easy to understand.</p> <p><img loading="lazy" class="alignnone size-full wp-image-16312" src="https://phppot.com/wp-content/uploads/2022/03/php-compress-image-files-2.jpg" alt width="300" height="301" srcset="https://phppot.com/wp-content/uploads/2022/03/php-compress-image-files-2.jpg 300w, https://phppot.com/wp-content/uploads/2022/03/php-compress-image-files-2-150x150.jpg 150w" sizes="(max-width: 300px) 100vw, 300px"><br />This section describes the steps to set up this example in a development environment.</p> <h3>Step 1: Import database script</h3> <p>Import this SQL script into your database table. It creates a tbl_image table to run this example. It will have the image name and its path on upload.</p> <p>It also adds the index for primary key settings and auto_increament flag settings.</p> <p class="code-heading">sql/structure.sql</p> <pre class="prettyprint"><code class="language-sql"> -- -- Database: `image_upload` -- -- -- Table structure for table `tbl_image` -- CREATE TABLE `tbl_image` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `image` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Indexes for dumped tables -- -- -- Indexes for table `tbl_image` -- ALTER TABLE `tbl_image` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_image` -- ALTER TABLE `tbl_image` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; </code></pre> <h3>Step 2: Design image upload form</h3> <p>This code displays the HTML form with the option to <a href="https://phppot.com/php/php-image-upload-with-size-type-dimension-validation/">upload the image</a>. The HTML <em>accept</em> attribute limits the file type to allow only images to choose from.</p> <p>The form-submit action calls the <a href="https://phppot.com/php/bootstrap-contact-form-with-javascript-validation-and-php/">JavaScript validation</a>. It ensures that the file input is not empty.</p> <p>It targets the endpoint to optimize images by the compressing process. After a successful PHP compress image process, it <a href="https://phppot.com/php/extract-content-using-php-and-preview-like-facebook/">shows a preview of the image</a>.</p> <p class="code-heading">index.php (Image upload Form HTML)</p> <pre class="prettyprint"><code class="language-sql"> <html> <head> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> <h1>PHP Image Compress</h1> <div class="form-container"> <form class="form-horizontal" action="" method="post" id="image" enctype="multipart/form-data" name="form" onsubmit="return validateImage()"> <label>Choose image to compress</label> <div Class="input-row"> <input type="file" name="image" id="file" class="file" value="" accept=".jpg, .jpeg, .png, .gif"> </div> <?php if (! empty($result[0]["image"])) { ?> <!-- PHP image compress preview --> <img src="<?php echo $result[0]["image"] ;?>" class="img-preview" alt="photo"> <?php } ?> <div class="input-row"> <input type="submit" name="send" value="Upload" class="btn"> <div id="response" class="<?php if(!empty($response["type"])) { echo $response["type"] ; } ?>"> <?php if(!empty($response["message"])) { echo $response["message"]; } ?> </div> </div> </form> </div> </div> <script src="jquery-3.2.1.min.js"></script> <script> function validateImage() { var InputFile = document.forms["form"]["image"].value; if (InputFile == "") { error = "No source found"; $("#response").html(error).addClass("error");; return false; } return true; } </script> </body> </html> </code></pre> <h3>Process PHP compress image action</h3> <p>This PHP code is at the beginning of the landing page named <em>index.php</em>. It requests the PHP compress image action once the user submits the form.</p> <p>First, it calls the <em>compressImage()</em> function to resize. Thereby, it optimizes and stores the image into a folder. Once the image is successfully stored in the folder, then the path will be stored in the database.</p> <p class="code-heading">index.php (PHP compress image action)</p> <pre class="prettyprint"><code class="language-php"> <?php namespace Phppot; require_once __DIR__ . '/lib/ImageModel.php'; $imageModel = new ImageModel(); if (isset($_POST['send'])) { $source = $_FILES["image"]["tmp_name"]; $destination = "uploads/" . $_FILES["image"]["name"]; $response = $imageModel->compressImage($source, $destination, 90); if (!empty($response)) { $id = $imageModel->insertImage($destination); if (!empty($response)) { $response["type"] = "success"; $response["message"] = "Upload Successfully"; $result = $imageModel->getImageById($id); } } else { $response["type"] = "error"; $response["message"] = "Unable to Upload:$response"; } } ?> </code></pre> <h3>PHP model class to compress image</h3> <p>This PHP model class has functions to perform the following.</p> <p>The PHP image insertion function sets a target to place the uploaded image path.</p> <p>The compressImage() function is used to compress the uploaded file. The main focus of this process is to optimize the image quality.</p> <p class="code-heading">lib/ImageModel.php</p> <pre class="prettyprint"><code class="language-sql"> <?php namespace Phppot; use Phppot\DataSource; class ImageModel { private $conn; function __construct() { require_once 'DataSource.php'; $this->conn = new DataSource(); } function getAll() { $query = "SELECT * FROM tbl_image"; $result = $this->conn->select($query); return $result; } function getImageById($id) { $query = "SELECT * FROM tbl_image WHERE id=?"; $paramType = 'i'; $paramValue = array( $id ); $result = $this->conn->select($query, $paramType, $paramValue); return $result; } function insertImage($destination) { $insertId = 0; if (! empty($destination)) { $query = "INSERT INTO tbl_image(name,image) VALUES(?,?)"; $paramType = 'ss'; $paramValue = array( $_FILES["image"]["name"], $destination ); $insertId = $this->conn->insert($query, $paramType, $paramValue); } return $insertId; } function compressImage($sourceFile, $outputFile, $outputQuality) { $imageInfo = getimagesize($sourceFile); if ($imageInfo['mime'] == 'image/gif') { $imageLayer = imagecreatefromgif($sourceFile); } else if ($imageInfo['mime'] == 'image/jpeg') { $imageLayer = imagecreatefromjpeg($sourceFile); } else if ($imageInfo['mime'] == 'image/png') { $imageLayer = imagecreatefrompng($sourceFile); } $response = imagejpeg($imageLayer, $outputFile, $outputQuality); return $response; } } ?> </code></pre> <h2>Output: PHP image compress</h2> <p>The below screenshot shows the output of this PHP compress image example. It displays a choose file option to upload an image via an HTML form.</p> <p>It shows a preview of the uploaded image after form submission.<br /><img loading="lazy" class="alignnone size-large wp-image-16314" src="https://phppot.com/wp-content/uploads/2022/03/image-compress-output-1-550x298.jpg" alt width="550" height="298" srcset="https://phppot.com/wp-content/uploads/2022/03/image-compress-output-1-550x298.jpg 550w, https://phppot.com/wp-content/uploads/2022/03/image-compress-output-1-300x163.jpg 300w, https://phppot.com/wp-content/uploads/2022/03/image-compress-output-1-768x417.jpg 768w, https://phppot.com/wp-content/uploads/2022/03/image-compress-output-1.jpg 800w" sizes="(max-width: 550px) 100vw, 550px"></p> <h2>Use case scenarios that require ‘PHP compress image’</h2> <p>There are some scenarios that need to have media files in optimal quality. In such cases, this PHP compress image utility will be useful to have lightweight images.</p> <ul> <li>Online photo gallery application.</li> <li>Applications that create and maintain multiple thumbnails for each image.</li> <li>When the user uploads heavy images that exceed the allowed limit.</li> </ul> <h2>Conclusion</h2> <p>I hope, it is useful for you to learn the PHP compress image process. We have seen the purpose and the necessity of this job in a PHP application.</p> <p>The use case scenarios discussed above justify the importance of having compressed images.</p> <p>The examples we have seen may help to know the steps to implement. It will make you create your own image file util to do PHP compress image action.<br /><a class="download" href="https://phppot.com/downloads/php-compress-image.zip">Download</a></p> <p> <!-- #comments --> </p> <div class="related-articles"> <h2>Popular Articles</h2> </p></div> <p> <a href="https://phppot.com/php/php-compress-image/#top" class="top">↑ Back to Top</a> </p> </div> https://www.sickgaming.net/blog/2022/04/11/php-compress-image-optimize-resize-and-upload/ |