note 39850 added to function.imagecopyresized
| From: | schuele2 at istud dot fh-schmalkalden dot de | Date: | Thu, 12 Feb 2004 22:03:46 +0000 |
| Subject: | note 39850 added to function.imagecopyresized | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-65069@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/function.imagecopyresized.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+39850
Delete -- http://master.php.net/manage/user-notes.php?action=delete+39850&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+39850&report=yes
Search -- http://master.php.net/manage/user-notes.php