note 84241 deleted from function.getimagesize by tularis
| From: | tularis@php.net | Date: | Fri, 04 Jul 2008 23:55:22 +0000 |
| Subject: | note 84241 deleted from function.getimagesize by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-141182@lists.php.net to get a copy of this message | ||
Note Submitter: alastors at gmail dot com
Reason: useless
----
there are many snippets here trying to scale an image keeping aspect ratio, I believe every single
one is wrong!
I know very often everybody wants to make thumbnails.
this is what I come up with, it's a modified version from what I got from http://asymptomatic.net/2007/05/08/2608/create-thumbnail-in-php
<?
/**
* Creates a resized image from a source image, saves resized image to file
* @param string $src_filename Filename of the image to resize
* @param string $dst_filename Filename of the resized image to output
* @param integer $max_width Maximum width of resized image
* @param integer $max_height Maximum height of resized image
* @return boolean true on success, false on failure
*/
function createthumb($src_filename, $dst_filename, $max_w, $max_h) {
// Get information about the image
list($src_width, $src_height, $type, $attr) = getimagesize($src_filename);
// Load the image based on filetype
switch($type) {
case IMAGETYPE_JPEG:
$src_img = imagecreatefromjpeg($src_filename);
break;
case IMAGETYPE_PNG:
$src_img = imagecreatefrompng($src_filename);
break;
case IMAGETYPE_GIF:
$src_img = imagecreatefromgif($src_filename);
break;
default:
return false;
}
// Did the image fail to load?
if (!$src_img) {
return false;
}
// Calculate the output size based on the original's aspect ratio, this part is PERFECT!
$thumb_w = $max_w;
$thumb_h = $max_h;
$thumb_r = $max_w / $max_h;
$src_r = $src_width / $src_height;
if ($src_r > $thumb_r) {
$thumb_h /= $src_r;
} else if ($src_r < $thumb_r) {
$thumb_w *= $src_r;
}
// Create the output image and copy to source to it
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
if (($height < 100) || ($width < 100)) {
imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $src_width, $src_height);
} else {
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $src_width, $src_height);
}
/* Sharpen before save?
$sharpenMatrix = array( array(-1, -1, -1), array(-1, 16, -1), array(-1, -1, -1) );
$divisor = 8;
$offset = 0;
imageconvolution( $dst_img, $sharpenMatrix, $divisor, $offset );
//*/
// Get information about the output image
$path_info = pathinfo($dst_filename);
// Setup default return info
$return = true;
// Load the image based on filetype
switch (strtolower($path_info['extension'])) {
case 'jpg':
case 'jpeg':
imagejpeg($dst_img, $dst_filename);
break;
case 'png':
imagepng($dst_img, $dst_filename);
break;
case 'gif':
imagegif($dst_img, $dst_filename);
break;
default:
$return = $false;
}
// Clean up memory
imagedestroy($dst_img);
imagedestroy($src_img);
return $return;
}
?>