Here is a sample usage:
Code: Select all
$uploaded_image = $_FILES["filename"];
$img_folder = $_APPLICATION['images_folder'];
$image = framework::resizeImage(600, 400, $uploaded_image, $img_folder);
$object->setImageFilename($image);
Code: Select all
/**
* Resize an uploaded image and return the filename
*
* @param Int $max_width
* @param int $max_height
* @param Array $temporary_file
* @param String $folder
* @param String $new_filename = 'random'
* @param Bool $delete_original = true
*
* @static
* @return String | False
**/
static function resizeImage($max_width, $max_height, $temporary_file, $folder, $new_filename = "random", $delete_original = true) {
// create a new random filename if specified
if ($new_filename == "random") $new_filename = framework::generateRandomString(40);
$tmp_name = $temporary_file['tmp_name'];
$original_name = $temporary_file['name'];
$file_ext = substr(strtolower(strrchr($original_name, '.')),1);
$new_filename = "$new_filename.$file_ext";
// make sure the image is a jpg or gif
if ($file_ext != "jpeg" && $file_ext != "jpg" && $file_ext != "gif"):
framework::setError("Unable to process $original_name. Supported file types are JPEG and GIF");
return false;
endif;
// move or copy the image
$image_name = "$folder/$new_filename";
if ($delete_original):
move_uploaded_file($tmp_name, $image_name);
else:
copy($tmp_name, $image_name);
endif;
// get the old height & width
list($width, $height) = getimagesize($image_name);
// determine by what percentage, if any, to shrink the image
if ($width >= $height && $width > $max_width ):
$percentage = (float) ( $max_width / $width );
elseif ($height >= $width && $height > $max_height):
$percentage = (float) ( $max_height / $height );
else:
$percentage = 1;
endif;
$new_width = $width * $percentage;
$new_height = $height * $percentage;
// create a new resized image with the same filename
$new_image = imagecreatetruecolor($new_width, $new_height);
if ($file_ext == "jpeg" || $file_ext == "jpg"):
$old_image = imagecreatefromjpeg("$image_name");
elseif ($file_ext == "gif"):
$old_image = imagecreatefromgif("$image_name");
endif;
// create the new image
imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($new_image, "$folder/$new_filename", 100);
// delete the un-resized image
if ($delete_original) unlink($image_name);
// return the new file name as confirmation
return $new_filename;
}