<?php
function createThumb($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);
$width = imagesx($resource);
$height = imagesy($resource);
/* 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);
switch ($ext)
{
case "png":
// integer representation of the color black (rgb: 0,0,0)
$background = imagecolorallocate($virtual_image, 0, 0, 0);
// removing the black from the placeholder
imagecolortransparent($virtual_image, $background);
// turning off alpha blending (to ensure alpha channel information
// is preserved, rather than removed (blending with the rest of the
// image in the form of black))
imagealphablending($virtual_image, false);
// turning on alpha channel information saving (to ensure the full range
// of transparency is preserved)
imagesavealpha($virtual_image, true);
break;
case "gif":
// integer representation of the color black (rgb: 0,0,0)
$background = imagecolorallocate($virtual_image, 0, 0, 0);
// removing the black from the placeholder
imagecolortransparent($virtual_image, $background);
break;
}
/* copy source image at a resized size */
imagecopyresampled($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
);
}