...

View Full Version : Resizing images (Problem with the math)

vern
09-27-2004, 03:24 AM
What I want to do is resize images. I could easily just make a function that resizes it 50% ... but then the output would be 50% no matter how big the image is. I want to set a value for max width and height, but I have trouble doing the math/code to make sure the image doesn't grow bigger than the specified width and height, but still be as big, or close to the size of maximum. Anyone have any sample code? ideas? Thanks.

Celtboy
09-27-2004, 08:15 AM
I whipped this function up really quickly. It should do what you want

<?php
/*
* Name: resizeImage.php
* Version: 1.0
* Author: John Collins celtboy[at]gmail.com
*
* Purpose:
* Function takes an image and maximum width and height,
* and returns new width and height based on maximum values.
* It returns an associative array with the new width and height
*/
function resizeImage(\$max_width, \$max_height, \$image_file) {

/* image, width & height variables */
\$image_info = getImageSize(\$image_file);
\$width = \$image_info[0];
\$height = \$image_info[1];

/* our return values, default to current image dimensions */
\$ar_return = array();
\$ar_return["width"] = \$width;
\$ar_return["height"] = \$height;

/* Only perform if current dimensions are outside max */
if ((\$width > \$max_width) || (\$height > \$max_height)) {

if (\$width >= \$height) {
\$ar_return["width"] = (int)(\$max_width);
\$ar_return["height"] = (int)(\$height * (\$max_width / \$width));

} else {
\$ar_return["height"] = (int)(\$max_height);
\$ar_return["width"] = (int)(\$width * (\$max_height / \$height));
}

}

return \$ar_return;

} // resizeImage()
?>

Sample usage:

<?php
include("resizeImage.php");

/* Image Variables */
\$img_source = "my_image.jpg";
\$max_width = 200;
\$max_height = 400;

\$new_image_data = resizeImage(\$max_width, \$max_height, \$img_source);

/* Store results in simple vars */
\$width = \$new_image_data["width"];
\$height = \$new_image_data["height"];

/* Print resized image */
print "<img src=\"" . \$img_source . "\" width=\"" . \$width . "\" height=\"" . \$height . "\" alt=\"Image of: " . \$img_source . "\" />";

?>

hth,
-Celt

vern
09-28-2004, 05:43 AM
Much thanks. I'll hack it up when I get the time. Thanks for taking the time.