Function That Resizes Dimensions to Bounds [Helpers]
In one of my current projects at work I needed to load photos off the file system and resize them so that they fit within a specified set of bounds. So, obviously, I created a function to calculate it for me!
I also use an equivalent function for Intrepid Studios, which is provided after the PHP function.
/**
* Summary:
* Gets a new size that fits within
* a set bounds.
* Pass in false/null if you do not want bounds
* on a specific axis.
* Parameters:
* - mw : Max Width
* - mh : Max Height
* - ow : Original Width
* - oh : Original Height
* Returns:
* array['w'] : new width
* array['h'] : new height
*/
function sizeToBounds($mw, $mh, $ow, $oh) {
$returnSize = array("w" => 0, "h" => 0);
// Vars
$w = $ow;
$h = $oh;
$wr = $w / $mw; // w ratio
$hr = $h / $mh; // h ratio
// First size its width
if($mw && $w > $mw) {
// Set width
$w = $mw;
$h = intval($h / $wr);
}
// Then its height
if($mh && $h > $mh) {
// Set width
$w = intval($w / $hr);
$h = $mh;
}
$returnSize['w'] = $w;
$returnSize['h'] = $h;
return $returnSize;
}
Use it like so:
$newSize = sizeToBounds(200, 200, 230, 435);
echo ("w = " . $newSize['w'] . ", h = " . $newSize['h']);
// outputs
w = 91, h = 200
And the C# equivalent function:
// import System.Drawing
public static Size sizeToBounds(int mw, int mh, int nw, int nh)
{
double wr, hr;
// Scales image to bounds
wr = (double)nw / (double)mw;
hr = (double)nh / (double)mh;
// First width
if (mw != 0 && nw > mw)
{
nw = mw;
nh = (int)(nh / wr);
}
// Then, height
if (mh != 0 && nh > mh)
{
nh = mh;
nw = (int)(nw / hr);
}
return new Size(nw, nh);
}
Use it like so:
Size NewSize = sizeToBounds(200, 200, 230, 435);
Response.Write("w = " + NewSize.Width + ", h = " + NewSize.Height);
// outputs
w = 91, h = 200
How about a function that will just do everything for you? This PHP function will find the appropriate resized width and height for a photo on the file system.
/**
* Gets the new size for a photo,
* fit within a set xy bounds.
*/
function sizePhotoToBounds($mw, $mh, $img) {
if(!file_exists($img)) {
return false;
}
$s = getimagesize($img);
// Failed, no width, or no height
if(!$s || $s[0] == 0 || $s[1] == 0 ) {
return false;
} else {
// Everything's hunky dory
return sizeToBounds($mw, $mh, $s[0], $s[1]);
}
}
$img refers to the full path to the image file.
Enjoy!