I have a site and I want to upload an image and resize it because I have to put it into a div with a certain dimension.
For example my max-width is 200px and max-height is 100px
I want to upload the image and check width and height, if they are bigger than the max-width or max-height I want to find the size of the image to stay inside that div.
How can I resize proportionally the size of the image? I only want to find new width and new height in base of my div 200px*100px
This is my script:
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
list($width, $height, $type, $attr) = getimagesize($tmp);
if($width>200){
//too large I want to resize
}
if($height>100){
//too height I want to resize
}
echo(base_url().$path.$actual_image_name);
}
You can use the function below to stay inside a bounding box. EG 200x200. Just send in the filelocation and the max width and height. It will return an array where $ar[0]
is the new width and $ar[1]
is the new height.
Its written out in full so you can understand the math.
<?php
function returnSize($maxW,$maxH,$img) {
$maxW = ($maxW>0 && is_numeric($maxW)) ? $maxW : 0;
$maxH = ($maxH>0 && is_numeric($maxH)) ? $maxH : 0;
// File and new size
if (!file_exists($img)) {
$size[0]=0;
$size[1]=0;
return $size;
}
$size = getimagesize($img);
if ($maxW>0 && $maxH>0) {
if ($size[0]>$maxW) {
$scaleW = $maxW / $size[0];
} else {
$scaleW = 1;
}
if ($size[1]>$maxH) {
$scaleH = $maxH / $size[1];
} else {
$scaleH = 1;
}
if ($scaleW > $scaleH) {
$fileW = $size[0] * $scaleH;
$fileH = $size[1] * $scaleH;
} else {
$fileW = $size[0] * $scaleW;
$fileH = $size[1] * $scaleW;
}
} else if ($maxW>0) {
if ($size[0]>$maxW) {
$scaleW = $maxW / $size[0];
} else {
$scaleW = 1;
}
$fileW = $size[0] * $scaleW;
$fileH = $size[1] * $scaleW;
} else if ($maxH>0) {
if ($size[1]>$maxH) {
$scaleH = $maxH / $size[1];
} else {
$scaleH = 1;
}
$fileW = $size[0] * $scaleH;
$fileH = $size[1] * $scaleH;
} else {
$fileW = $size[0];
$fileH = $size[1];
}
$size[0] = $fileW;
$size[1] = $fileH;
return $size;
}
?>