note 39850 deleted from function.imagecopyresized by aidan
| From: | aidan@php.net | Date: | Mon, 04 Oct 2004 09:38:45 +0000 |
| Subject: | note 39850 deleted from function.imagecopyresized by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-77906@lists.php.net to get a copy of this message | ||
Note Submitter: schuele2 at istud dot fh-schmalkalden dot de
----
I needed a simple function, that resizes an uploaded image and writes it to a file. here's the
code that worked for me:
<?php
// Resize an image if it exceeds a predefined size.
function imageresize($filename,$maxwidth,$maxheight) {
if (is_file($filename)) { /* check if the file is really one ;) */
$fd = @fopen($filename,"r");
$image_string = fread($fd,filesize($filename));
fclose($fd);
unlink($filename); /* we need to delete the file,
because we want to replace
the original file with the
resized one */
$im = ImageCreateFromString($image_string);
$currwidth = ImageSX($im);
$currheight = ImageSY($im);
/* now we have to check if the image
is higher than wider and larger
than the defined size, then
calculte it and resize it proportional */
if ($currwidth > $currheight && $currwidth > $maxwidth) {
$percent = ($maxwidth * 100) / $currwidth;
$nwidth = $maxwidth;
$nheight = ($percent * $currheight) / 100;
} elseif ($currwidth < $currheight && $currheight > $maxheight) {
$percent = ($maxheight * 100) / $currheight;
$nheight = $maxheight;
$nwidth = ($percent * $currwidth) / 100;
}
$nwidth = intval($nwidth);
$nheight = intval($nheight);
/* ok. let's create the new smaller image
with calculated size... */
$newim = imagecreate ($nwidth, $nheight);
/* ...and put the lager image into the
smaller one. */
imagecopyresized($newim,$im,0,0,0,0,$nwidth,$nheight,$width,$height);
/* now save to file and clear up the memory ;) */
imagepng($newim,$filename);
ImageDestroy($im);
ImageDestroy($newim);
/* if you want, use the returned HTML-Code
and insert it into an <img>-tag */
return "width=\"".$nwidth."\"
height=\"".$nheight."\"";
} else {
/* if the file wasn't a file ;) return false */
return false;
}
}
?>
Have a nice time with it.