Home » , , » Simple Image Resize Calculator Function

Simple Image Resize Calculator Function

Written By Unknown on Rabu, 14 April 2010 | 23.11


Here is a simple function to calculate the width and height of an image given the constraints you want the image to fit in. This is great for creating thumbnails which need to fit into a specific height / width.

To call the function, pass in the current height / width of the image you’d like to resize along with the constrain dimensions of the final product. In this case, I’d like the thumbnail to fit within the constraints 125px X 125px. So, no matter what the dimensions returned will be within those confines.
If you don’t pass along a $constraintWidth or $constraintHeight [or pass them as 0], they will be set to the $width / $height.
Also, all parameters are assumed to be of the strict type int.
<?php
function getImageResizeDimensions($width,$height,$constraintWidth = 0,$constraintHeight = 0) {
$constraintWidth = ($constraintWidth === 0) ? $width : $constraintWidth;
$constraintHeight = ($constraintHeight === 0) ? $height : $constraintHeight;
if (($width > $constraintWidth) || ($height > $constraintHeight)) {
while (($constraintWidth < $width) || ($constraintHeight < $height)) {
if ($constraintWidth < $width) {
$height = floor((($constraintWidth * $height) / $width));
$width = $constraintWidth;
}
if ($constraintHeight < $height) {
$width = floor((($constraintHeight * $width) / $height));
$height = $constraintHeight;
}
}
retur
}
n array ($width,$height);
}
$imageURI = "/path/to/image.jpg";
list ($width,$height) = getimagesize($imageURI);
list ($newWidth,$newHeight) = getImageResizeDimensions($width,$height,125,125);
echo "newWidth: $newWidth\n";
echo "newHeight: $newHeight\n";
?>
Share this article :

Posting Komentar

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger