Friday, 6 October 2017

How to optimize images for SEO - PHP

It is common to upload the images dynamically to the websites. But when we upload the large file size image on the website, it consumes a lot of time while loading. So the developer should write the code to reduce the image file size while uploading the image dynamically to the website. Using PHP, you can easily reduce the file size of those uploaded images during  time of upload. Of course, when reducing the file size we sacrifice the image quality.

seo-image-optimization

Code to reduce file size for the image:
<?php 
 function compress($source, $destination, $quality) {

  $info = getimagesize($source);

  if ($info['mime'] == 'image/jpeg') 
   $image = imagecreatefromjpeg($source);

  elseif ($info['mime'] == 'image/gif') 
   $image = imagecreatefromgif($source);

  elseif ($info['mime'] == 'image/png') 
   $image = imagecreatefrompng($source);

  imagejpeg($image, $destination, $quality);

  return $destination;
 }

 $source_img = 'source.jpg';
 $destination_img = 'destination .jpg';

 $d = compress($source_img, $destination_img, 90);
 ?>
$d = compress($source_img, $destination_img, 90);
This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).
$info = getimagesize($source);
The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.
Example:
$info = getimagesize($source);
print_r($info);
Output:
Array ( [0] => 1280 [1] => 768 [2] => 2 [3] => width="1280" height="768" [bits] => 8 [channels] => 3 [mime] => image/jpeg )
$image = imagecreatefromjpeg($source);
$image = imagecreatefromgif($source);
$image = imagecreatefrompng($source);
All the above functions are used to create a new image from the given file or URL. These functions are used to return an image identifier representing the image obtained from the given file name.
imagejpeg($image, $destination, $quality);
imagejpeg() function is used to create a JPEG file from the given image.
Syntax: imagejpeg ( $source_image, $destination_image, $quality )
Quality ($quality): quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default range is 75.
Note:
The GD library is used for dynamic image creation. From PHP we use with the GD library to create GIF, PNG or JPG. This is very important to run all the image creation function in PHP. If your server doesn’t support the GD library then all the above functionality related to the image creation will not work.
Complete code to reduce the image file size:
<?php
 $name = ''; $type = ''; $size = ''; $error = '';
 function compress_image($source_url, $destination_url, $quality) {

  $info = getimagesize($source_url);

      if ($info['mime'] == 'image/jpeg')
           $image = imagecreatefromjpeg($source_url);

      elseif ($info['mime'] == 'image/gif')
           $image = imagecreatefromgif($source_url);

     elseif ($info['mime'] == 'image/png')
           $image = imagecreatefrompng($source_url);

      imagejpeg($image, $destination_url, $quality);
  return $destination_url;
 }

 if ($_POST) {

      if ($_FILES["file"]["error"] > 0) {
           $error = $_FILES["file"]["error"];
      } 
      else if (($_FILES["file"]["type"] == "image/gif") || 
   ($_FILES["file"]["type"] == "image/jpeg") || 
   ($_FILES["file"]["type"] == "image/png") || 
   ($_FILES["file"]["type"] == "image/pjpeg")) {

           $url = 'destination .jpg';

           $filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
           $buffer = file_get_contents($url);

           /* Force download dialog... */
           header("Content-Type: application/force-download");
           header("Content-Type: application/octet-stream");
           header("Content-Type: application/download");

   /* Don't allow caching... */
           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

           /* Set data type, size and filename */
           header("Content-Type: application/octet-stream");
           header("Content-Transfer-Encoding: binary");
           header("Content-Length: " . strlen($buffer));
           header("Content-Disposition: attachment; filename=$url");

           /* Send our file... */
           echo $buffer;
      }else {
           $error = "Uploaded image should be jpg or gif or png";
      }
 }
?>
<html>
     <head>
          <title>Php code compress the image</title>
     </head>
     <body>

  <div class="message">
                     <?php
                      if($_POST){
                          if ($error) {
                              ?>
                              <label class="error"><?php echo $error; ?></label>
                        <?php
                              }
                         }
                     ?>
                 </div>
  <fieldset class="well">
                  <legend>Upload Image:</legend>                
   <form action="" name="myform" id="myform" method="post" enctype="multipart/form-data">
    <ul>
                <li>
      <label>Upload:</label>
                                   <input type="file" name="file" id="file"/>
     </li>
     <li>
      <input type="submit" name="submit" id="submit" class="submit btn-success"/>
     </li>
    </ul>
   </form>
  </fieldset>
 </body>
</html>
I hope the above-mentioned PHP code could be beneficial in reducing the image file size while uploading it to save your precious time. I believe the topic discussed here is quite useful to everyone who reads it!
Source: https://www.apptha.com/blog/how-to-reduce-image-file-size-while-uploading-using-php-code/

About the Author

Unknown

Author & Editor

Hi Friends, I am Kayalvizhi doing Computer science engineering in Madurai. My hobbies are browsing, reading books and playing puzzles. I love programming. Read more

No comments:

Post a Comment

 
KayalSpot © 2015 - Designed by Templateism.com