Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] PHP compress image optimize, resize and upload

#1
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">
&lt;?php
$sourceFile = 'image.jpg';
$outputFile = 'compressed-image.jpg';
$outputQuality = 60;
$imageLayer = imagecreatefromjpeg($sourceFile);
imagejpeg($imageLayer, $outputFile, $outputQuality);
?&gt;
</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/20...50x150.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">
&lt;html&gt;
&lt;head&gt;
&lt;link href="style.css" rel="stylesheet" type="text/css" /&gt;
&lt;/head&gt;
&lt;body&gt; &lt;div class="container"&gt; &lt;h1&gt;PHP Image Compress&lt;/h1&gt; &lt;div class="form-container"&gt; &lt;form class="form-horizontal" action="" method="post" id="image" enctype="multipart/form-data" name="form" onsubmit="return validateImage()"&gt; &lt;label&gt;Choose image to compress&lt;/label&gt; &lt;div Class="input-row"&gt; &lt;input type="file" name="image" id="file" class="file" value="" accept=".jpg, .jpeg, .png, .gif"&gt; &lt;/div&gt; &lt;?php if (! empty($result[0]["image"])) { ?&gt; &lt;!-- PHP image compress preview --&gt; &lt;img src="&lt;?php echo $result[0]["image"] ;?&gt;" class="img-preview" alt="photo"&gt; &lt;?php } ?&gt; &lt;div class="input-row"&gt; &lt;input type="submit" name="send" value="Upload" class="btn"&gt; &lt;div id="response" class="&lt;?php if(!empty($response["type"])) { echo $response["type"] ; } ?&gt;"&gt; &lt;?php if(!empty($response["message"])) { echo $response["message"]; } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="jquery-3.2.1.min.js"&gt;&lt;/script&gt; &lt;script&gt; function validateImage() { var InputFile = document.forms["form"]["image"].value; if (InputFile == "") { error = "No source found"; $("#response").html(error).addClass("error");; return false; } return true; } &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</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&nbsp;<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">
&lt;?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-&gt;compressImage($source, $destination, 90); if (!empty($response)) { $id = $imageModel-&gt;insertImage($destination); if (!empty($response)) { $response["type"] = "success"; $response["message"] = "Upload Successfully"; $result = $imageModel-&gt;getImageById($id); } } else { $response["type"] = "error"; $response["message"] = "Unable to Upload:$response"; }
} ?&gt;
</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">
&lt;?php
namespace Phppot; use Phppot\DataSource; class ImageModel
{ private $conn; function __construct() { require_once 'DataSource.php'; $this-&gt;conn = new DataSource(); } function getAll() { $query = "SELECT * FROM tbl_image"; $result = $this-&gt;conn-&gt;select($query); return $result; } function getImageById($id) { $query = "SELECT * FROM tbl_image WHERE id=?"; $paramType = 'i'; $paramValue = array( $id ); $result = $this-&gt;conn-&gt;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-&gt;conn-&gt;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; }
}
?&gt;
</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/20...00x163.jpg 300w, https://phppot.com/wp-content/uploads/20...68x417.jpg 768w, https://phppot.com/wp-content/uploads/20...tput-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/...nd-upload/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016