Ruby Tuesday wrote:
I have a section(185pixelsx 185pixels) in my web page to display an image
that is stored in a directory. Using php, how do you resize so if:
the image dimension is smaller(width and height is less than 185pixels),
display it in the center of the section
if the width OR height is larger than 185pixel, resize them with aspect
ratio maintained so both width and height is <= 185pixels. Then display it
in the center of the section.
Hi,
I just wrote a function doing this yesterday.
-->
http://www.hightech-board.de/thread....8101#post18101
(Sorry, the explanations are in german, but you'll understand the php
code, I think)
It resizes jpgs and pngs, if GD2 is installed and gifs, too, if there
is gif reading support.
Greetz
Paul.
P.S.: And here the code without Highlighting... ;-)
================================================== ========
<?php
function resizeImg($imgPath, $maxWidth = 100, $maxHeight = 100,
$directOutput = false, $quality = 90, $verbose = false)
{
// get image size infos (0 width and 1 height,
// 2 is (1 = GIF, 2 = JPG, 3 = PNG)
$size = getimagesize($imgPath);
// break and return false if failed to read image infos
if(!$size){
if($verbose && !$directOutput)echo "<br />Not able to read
image infos.<br />";
return false;
}
// relation: width/height
$relation = $size[0]/$size[1];
// maximal size (if parameter == false, no resizing will be made)
$maxSize = array(
$maxWidth?$maxWidth:$size[0],
$maxHeight?$maxWidth:$size[1]
);
// declaring array for new size (initial value = original size)
$newSize = $size;
// width/height relation
$relation = array($size[1]/$size[0], $size[0]/$size[1]);
// get new dimension, if necessary
$i = 0;
while((($newSize[0] > $maxSize[0]) || ($newSize[1] >
$maxSize[1])) && ($i < 2))
{
$newSize[$i] = intval(min($newSize[$i], $maxSize[$i]));
$newSize[(($i+1)%2)] = intval($relation[$i]*$newSize[$i]);
$i++;
}
// need to resize?
if(!$i){
if($verbose && !$directOutput)echo "<br />No need to resize.<br
/>";
if(!$directOutput)return true;
}
// create image
switch($size[2])
{
case 1:
if(function_exists("imagecreatefromgif"))
{
$originalImage = imagecreatefromgif($imgPath);
}else{
if($verbose && !$directOutput)echo "<br />No GIF support
in this php installation, sorry.<br />";
return false;
}
break;
case 2: $originalImage = imagecreatefromjpeg($imgPath); break;
case 3: $originalImage = imagecreatefrompng($imgPath); break;
default:
if($verbose && !$directOutput)echo "<br />No valid image
type.<br />";
return false;
}
// create new image
$resizedImage = imagecreatetruecolor($newSize[0], $newSize[1]);
imagecopyresampled(
$resizedImage, $originalImage,
0, 0, 0, 0,
$newSize[0], $newSize[1], $size[0], $size[1]);
// output or save
if($directOutput){
imagejpeg($resizedImage);
}else{
imagejpeg($resizedImage,
preg_replace("/\.([a-zA-Z]{3,4})$/",".jpg",$imgPath), $quality);
}
// return true if successfull
return true;
}
?>
================================================== ============