Saturday, October 3, 2009

Image Resize or Thumbnail Generation

function Createthumb($name,$image_path,$thumb_path,$thumbWidth){

$system=explode('.',$name);

if(preg_match('/jpg|jpeg/',$system[1])){
$src_img=imagecreatefromjpeg($image_path);
}
if(preg_match('/png/',$system[1])){
$src_img=imagecreatefrompng($image_path);
}
if(preg_match('/gif/',$system[1])){
$src_img=imagecreatefromgif($image_path);
}

$width = imagesx($src_img);
$height = imagesy($src_img);

// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );

// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image
imagecopyresized( $tmp_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

// save thumbnail into a file
if(preg_match("/png/",$system[1])) {
imagepng($tmp_img,$thumb_path);
} else if(preg_match("/jpg|jpeg/",$system[1])) {
imagejpeg($tmp_img,$thumb_path);
}else if(preg_match("/gif/",$system[1])) {
imagegif($tmp_img,$thumb_path);
}


}