Php Programming Code Examples
Php > Arrays Code Examples
Simple way of scaling any image to fit either given width or height.
Simple way of scaling any image to fit either given width or height.
If you are fed up of always manually manipulating the layout with images, try this code:
<?
$width=300; //size in pixel
$height=300; //size in pixel
$image="sample.jpg";
<img src="<? echo $image ?>" border="0" <? check_image($image) ?> >
?>
Include this function in your scripts:
<?
function check_image($image,$cfgMaxImgWidth,$cfgMaxImgHeight)
{
global $strNewImageSize,$cfgMaxImgWidth,$cfgMaxImgHeight;
$imageAttributes=$strNewImageSize="";
$imageAttributes=GetImageSize($image);
if($imageAttributes[0]>$cfgMaxImgWidth)
{
$factor=$imageAttributes[0]/$cfgMaxImgWidth;
$newImgWidth=$cfgMaxImgWidth;
$newImgHeight=round($imageAttributes[1]/$factor);
$strNewImageSize="width=$newImgWidth height=$newImgHeight";
}
elseif($imageAttributes[1]>$cfgMaxImgHeight)
{
$factor=$imageAttributes[1]/$cfgMaxImgHeight;
$newImgHeight=$cfgMaxImgHeight;
$newImgWidth=round($imageAttributes[0]/$factor);
$strNewImageSize="width=$newImgWidth height=$newImgHeight";
}
echo $strNewImageSize;
}
?>
What happens: the given image will be scaled either if it is too wide or too high or both, down
to the set values. It will be nicely scaled by maintaining the aspect ratio.