Home > PHP > Make thumb using php with respect the ratio width and height

Make thumb using php with respect the ratio width and height

In this post i would like to explain how to create thumbnails with respect to ratio of width and height. Rather than scaling images to create a thumbnails and we can reduce the page load time also. With simple code of php we can get the thumbnails of images.

 make thumb using php with respect the ratio width and height | Anil Labs

make thumb using php with respect the ratio width and height | Anil Labs


 

PHP Code

 

<?php
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
  // open the directory
  $dir = opendir( $pathToImages );

  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' )
    {
      echo "Creating thumbnail for {$fname} <br />";

      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
    }
  }
  // close the directory
  closedir( $dir );
}
// call createThumb function and pass to it as parameters the path
// to the directory that contains images, the path to the directory
// in which thumbnails will be placed and the thumbnail's width.
// We are assuming that the path will be a relative path working
// both in the filesystem, and through the web for links
createThumbs("images/","images/thumb/",400);
?>

Hope that it will be useful.

You may also like
Website uptime monitoring using PHP script
Understanding the basic need of MVC architecture
How to convert feeds to html using javascript and php
Multi-language support for web application with MySql and PHP

8 Responses

  1. Pingback : [WATCH]: ☺ David MeShow – Extreme Beatbox (No Instrument)

  2. Pingback : FEBRUARY 13 – WEEK 100 RESULTS | Causes of high cholesterol Blog

  3. Pingback : 13. February – Daily Report | Causes of high cholesterol Blog

  4. Pingback : FEBRUARY 13 – DAILY REPORT | Causes of high cholesterol Blog

  5. Pingback : Case Study : Upload and crop images with specific dimensions - Anil Labs

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.