• Top
  • Reply

Creating Thumbnails in PHP

This is a common question that web developers come accross, and i found a great tutorial online to show me how to do that. All i have done below is take the tutriol from http://www.bolducpress.com/tutorials/create-cropped-thumbnails-with-gd-library/ and converted this into a function.

Full credits go to BolducPress

function createthumb($imgSrc,$filename,$thumbSize)
{

    $system=explode(".", $imgSrc);

    //getting the image dimensions
    list($width, $height) = getimagesize($imgSrc);

    //saving the image into memory (for manipulation with GD Library)
    $myImage = imagecreatefromjpeg($imgSrc);

    ///--------------------------------------------------------
    //setting the crop size
    //--------------------------------------------------------
    if($width > $height) $biggestSide = $width;
    else $biggestSide = $height;

    //The crop size will be half that of the largest side
    $cropPercent = .5;
    $cropWidth   = $biggestSide*$cropPercent;
    $cropHeight  = $biggestSide*$cropPercent;

    //getting the top left coordinate
    $c1 = array("x"=>($width-$cropWidth)/2, "y"=>($height-$cropHeight)/2);


    //--------------------------------------------------------
    // Creating the thumbnail
    //--------------------------------------------------------
    $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
    imagecopyresampled($thumb, $myImage, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);

    if (preg_match("/png/",$system[sizeof($system) - 1]))
    {
        imagepng($thumb, $filename); 
    } else {
        imagejpeg($thumb, $filename); 
    }

    imagedestroy($thumb);
    imagedestroy($myImage); 
}

You will need GD library for this to work.

By

12th Feb 2011
© 2011 Shahmir Javaid - http://shahmirj.com/blog/12


Back to Top
All content is © copyrighted, unless stated otherwise.
Subscribe, @shahmirj, Shahmir Javaid+