Wednesday, December 18, 2013

Generating thumbnail for an image using PHP

This is a basic tutorial for beginners. In this tutorial we are going to learn how to generate a thumbnail from an image. We are going to write a simple function, which would convert any image (gif, jpg or png) into thumbnail. This function creates the thumbnail image from the source image. The actual weight and height of the thumbnail are calculated based the proportional values of the source image width and height respectively.

The following is the code:

<?php
// Function for resizing jpg, gif, and png image files

function image_resize($original, $thumb, $w, $h, $ext) {
    list($w_org, $h_org) = getimagesize($original);
    $scale_ratio = $w_org / $h_org;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;

    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    
if ($ext == "gif"){ 
      $img = imagecreatefromgif($original);
    } else if($ext =="png"){ 
      $img = imagecreatefrompng($original);
    } else if($ext =="jpg" or $ext =="jpeg"){ 
      $img = imagecreatefromjpeg($original);
    }else{
  echo "Only images of type jpg, gif and png are supported.";
  exit;
}
    $true_img = imagecreatetruecolor($w, $h);
    imagecopyresampled($true_img, $img, 0, 0, 0, 0, $w, $h, $w_org, $h_org);
    imagejpeg($true_img, $thumb, 80);
}


$file_name = "sample.gif"; // name of the source image file
$arr = explode(".", $file_name); // Split file name into an array
$fileExt = end($arr); // Get the file extension from the array's last element

$thumb = "thumb_$fileName"; // name of the thumb to be generated 
$width = 100; // maximum width of the thumbnail to be created
$height = 100; // maximum height of the thumbnail to be created

image_resize($file_name, $thumb, $width, $height, $fileExt); //Call image resize function

//Display original image
echo "Originaal Image: <br/>";
echo "<img src='$file_name'><br/><br/>";

//Display image thumbnail generated
echo "Thumb Image: <br/>";
echo "<img src='$thumb'>";
?>

No comments :

Post a Comment