Web Development Tips

PHP – Create thumbnail image

Posted by: slvramesh on: June 15, 2011

PHP – Create thumbnail image
/** Common functions */
function make_thumb($name, $src, $dest, $new_w, $new_h) {
$border=false;
$transparency=true;
$base64=false;

if(!file_exists($src.DS.$name))
return false;

$arr = split("\.", $name);
$ext = strtolower($arr[count($arr)-1]);

if($ext=="jpeg" || $ext=="jpg"){
$img = @imagecreatefromjpeg($src.DS.$name);
} elseif($ext=="png"){
$img = @imagecreatefrompng($src.DS.$name);
} elseif($ext=="gif") {
$img = @imagecreatefromgif($src.DS.$name);
}
if(!$img)
return $name;

$old_x = imageSX($img);
$old_y = imageSY($img);

// proportionately - re-size image
/*
if($old_x < $new_w && $old_y $old_y) {
$thumb_w = $new_w;
$thumb_h = floor(($old_y*($new_h/$old_x)));
} elseif ($old_x < $old_y) {
$thumb_w = floor($old_x*($new_w/$old_y));
$thumb_h = $new_h;
} elseif ($old_x == $old_y) {
$thumb_w = $new_w;
$thumb_h = $new_h;
}*/

$thumb_w = $new_w;
$thumb_h = $new_h;

$thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
$thumb_h = ($thumb_h= 0) {
//its transparent
$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
$trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
imagefill($new_img, 0, 0, $trnprt_indx);
imagecolortransparent($new_img, $trnprt_indx);
}
}
else{
$white = imagecolorallocate($new_img, 255, 255, 255);
Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
imagefilledrectangle($new_img, 0, 0, $new_w, $new_h, $white);
}
} else {
$white = imagecolorallocate($new_img, 255, 255, 255);
Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
imagefilledrectangle($new_img, 0, 0, $thumb_w, $thumb_h, $white);
}

imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);

if($border) {
$black = imagecolorallocate($new_img, 0, 0, 0);
imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
}

$dest_filename = $arr[0].'_'.$new_w.'_'.$new_h.'.'.$ext;
$dest_filename = strtolower($dest_filename);
$dest_path = $dest.DS.$dest_filename;

if($base64) {
ob_start();
imagepng($new_img);
$img = ob_get_contents();
ob_end_clean();
$return = base64_encode($img);
} else {
if($ext=="jpeg" || $ext=="jpg"){
imagejpeg($new_img, $dest_path);
} elseif($ext=="png"){
imagepng($new_img, $dest_path);
} elseif($ext=="gif") {
imagegif($new_img, $dest_path);
}
}
imagedestroy($new_img);
imagedestroy($img);

//Delete the orginal file
if($src==$dest)
@unlink($src.DS.$name);
return $dest_filename;
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.