Page 1 of 1

Image Resize Function

Posted: Mon Aug 18, 2008 5:53 am
by mrgooding
Hi All

I'm trying to implement a function to resize images on the fly - I found a tutorial on
http://www.websitepublisher.net/article ... ge-resize/ which seems to be pretty good - Here is the code

Code: Select all

<?php
 
//declare your variables
 
function imgResize($width, $height, $target) {
//takes the larger size of the width and height and applies the formula. Your function is designed to work with any image in any size. 
if ($width > $height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);
}
 
//gets the new value and applies the percentage, then rounds the value
 
$width = round($width * $percentage);
$height = round($height * $percentage);
//returns the new sizes in html image tag format...this is so you can plug this function inside an image tag so that it will set the image to the correct size, without putting a whole script into the tag. 
return "width=\"$width\" height=\"$height\"";
 
}
 
?>
 
My problem is that the function doesn't seem to work! I use the function in this way:

Code: Select all

Echo "<td><img src='$mpic2' imgResize($mpicture[0], $mpicture[1], 100)></td>";
After having defined $mpicture as below:

Code: Select all

$mpicture = getimagesize($mpic2);
The images display fine, but aren't resized - i've tried playing around with the location of the imgResize function, but it doesn't seem to make any difference. Anyone have any ideas why this doesn't work? If so, I appreciate your time.

Re: Image Resize Function

Posted: Mon Aug 18, 2008 6:25 am
by onion2k
You need to escape out of the double quotes when you call the resize function.

Code: Select all

echo "<td><img src='$mpic2' ".imgResize($mpicture[0], $mpicture[1], 100)."></td>";
For the record, what you're doing there will look terrible. It's not actually resizing the images at all, it's just forcing the browser to display them at the wrong size. Browsers shrink images using a nearest neighbour algorithm that produces dreadful results. The browser will also have to download the entire full size image in order to display the small version, so the bandwidth used will be the same as if the user had viewed the image at the full size. I wouldn't recommend it.

Re: Image Resize Function

Posted: Mon Aug 18, 2008 6:29 am
by mrgooding
Aah, thanks!

I guess there has to be a far more elegant way of doing this - the only other way I could think of doing it was to resize the image when users uploaded them.

I'll have to look into a better solution when i've sorted out a few other bugs!

Thanks for your help though, much appreciated :)