The Blog of a Programmer
Image Resizing Using PHP and the GD library
I’m developing a new system core, can’t really say what it’s about but I’m having some fun doing it. Coding it is interesting, I’m getting to pull out and update some of my php code. Below is some code for image resizing, I use config files to set some default information like directories to save to and max width/height requirements. Also the entire system uses language files so I don’t output the text directly either, except for what I’m going to remove which is the uploaded file information.
Resize JPG images using the GD library and PHP.
function get_image_information($key) {
global $thumbnail_dest, $image_dest, $thumb_max_height, $thumb_max_width, $image_max_height, $image_max_width;
$filename = $_FILES[$key]["name"];
$file_type = $_FILES[$key]["type"];
$file_tmpname = $_FILES[$key]["tmp_name"];
$file_error = $_FILES[$key]["error"];
$file_size = $_FILES[$key]["size"];if($file_error == 0 && $file_size > 0) {
if($file_type == “image/pjpeg” $file_type == “image/jpeg” $file_type == “image/jpg”) {
$image_name = md5(time() . rand(1001,10000)) . “.jpg”;
$thumb_dest = $thumbnail_dest . $image_name;
$image_dest = $image_dest . $image_name;
create_image($file_tmpname, $thumb_max_height, $thumb_max_width, $thumb_dest);
create_image($file_tmpname, $image_max_height, $image_max_width, $image_dest);
return “thumbs/” . $image_name;
} else {
$success .= file_upload_success_1 . $filename . file_upload_success_2 . “
“;
$success .= “We can only accept jpg uploads. Upload Failed.”;
return $success;
}
} else {
if($file_error == 1) {
echo $file_upload_fail_1;
} elseif($file_error == 2) {
echo $file_upload_fail_2;
} elseif($file_error == 3) {
echo $file_upload_fail_3;
} elseif($file_error == 4) {
echo $file_upload_fail_4;
} elseif($file_error == 6) {
echo $file_upload_fail_6;
}
return false;
}
}
function create_image($image, $max_width, $max_height, $dest) {
$image = imagecreatefromjpeg($image);
if ($image === false) {
die (‘Unable to open image’);
}$width = imagesx($image);
$height = imagesy($image);if($width < $max_width && $height < $max_height) {
$new_width = $width;
$new_height = $height;
} else {
$scale = min($max_width/$width, $max_height/$height);
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
}$image_resized = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_resized, $dest, 90);
}
| This entry was posted by JuanJose on November 26, 2006 at 2:48 am, and is filed under Development, Linux Command Line, PHP, Programming. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |