Home  • Programming • PHP

How to Create Thumbnail Images using PHP?

<?php
function create_thumb($src,$dest,$desired_width = false, $desired_height = false)
{
    /*If no dimenstion for thumbnail given, return false */
    if (!$desired_height&&!$desired_width) return false;
    $fparts = pathinfo($src);
    $ext = strtolower($fparts['extension']);
    /* if its not an image return false */
    if (!in_array($ext,array('gif','jpg','png','jpeg'))) return false;

    /* read the source image */
    if ($ext == 'gif')
        $resource = imagecreatefromgif($src);
    else if ($ext == 'png')
        $resource = imagecreatefrompng($src);
    else if ($ext == 'jpg' || $ext == 'jpeg')
        $resource = imagecreatefromjpeg($src);
    
	list($width, $height, $type, $attr) = getimagesize($src);
   
    /* find the "desired height" or "desired width" of this thumbnail, relative to each other, if one of them is not given  */
    if(!$desired_height) $desired_height = floor($height*($desired_width/$width));
    if(!$desired_width)  $desired_width  = floor($width*($desired_height/$height));
  
    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width,$desired_height);
  
    /* copy source image at a resized size */
    imagecopyresized($virtual_image,$resource,0,0,0,0,$desired_width,$desired_height,$width,$height);
    
    /* create the physical thumbnail image to its destination */
    /* Use correct function based on the desired image type from $dest thumbnail source */
    $fparts = pathinfo($dest);
    $ext = strtolower($fparts['extension']);
    /* if dest is not an image type, default to jpg */
    if (!in_array($ext,array('gif','jpg','png','jpeg'))) $ext = 'jpg';
    $dest = $fparts['dirname'].'/'.$fparts['filename'].'.'.$ext;
    
    if ($ext == 'gif')
        imagegif($virtual_image,$dest);
    else if ($ext == 'png')
        imagepng($virtual_image,$dest,1);
    else if ($ext == 'jpg' || $ext == 'jpeg')
        imagejpeg($virtual_image,$dest,100);
    
    return array(
        'width'     => $width,
        'height'    => $height,
        'new_width' => $desired_width,
        'new_height'=> $desired_height,
        'dest'      => $dest
    );
}

?>

How to use?

$size=create_thumb("input_pic.jpg","output_pic.jpg",200);

//print_r($size);
echo "<img src='$size[dest]' />";
?>

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd