Forum Topic: Php: Image Resizing

(1,215 views • 8 replies)

This topic is 1 page long.

<< < > >>
None

Pilot-Doofy

Reply To Post Reply & Quote

Posted at: 12/22/05 10:37 PM

Pilot-Doofy NEUTRAL LEVEL 37

Sign-Up: 09/13/03

Posts: 12,275

PHP Main

Required Knowledge: Intermediate

First, you should be familiar with including files or retrieving files for execution on your server. Basic knowledge of the $_SERVER['DOCUMENT_ROOT'] element would definitely help, although it's far from required to understand and use this tutorial.

Let's define our maximum width and height that the image should be. You'll need to set something in compliance with your website's layout so that you don't get a tangled up table or whatever you're using for your design. Let's say your design is 700px wide, we should set the width max to something along the lines of 500 to promise plenty of extra room for error in other sections of the layout should they occur.

Let's store the filename of the image we want to edit in the $img_src variable:
$img_src = 'mypic.gif';

For the maximum dimensions I'm going to use constants. I suggest using them so that you can guaruntee it won't be affected later in the program.

define('MAX_WIDTH', 500);
define('MAX_HEIGHT', 400);

Now we've got our max dimensions. Feel free to set these to your heart's content. Now, we have to retrieve the image's dimensions. We can do this using the getimagesize() function which will return an array containing the width and height of the image.

$dims = getimagesize($img_src);
$old_width = $dims[0]; // The 1st (0) key holds the width
$old_height = $dims[1]; // The height is held in the 2nd (1) key

Now, let's check to make sure that the image needs to be resized. If it doesn't, we'll just return (or echo, your choice) the original image.

if ($old_width <= MAX_WIDTH && $old_height <= MAX_HEIGHT) {
return '<img src="' . $img_src . '" width="' . $old_width . '" height="' . $old_height . '">';
}

Now, I'm writing this tutorial to help us setup a function which can perform this task over and over. If you want to use it only once you can change the return statements to echo or whatever else you need to fit your application.

Now, we need to get the difference in the width and height versus the max width and max height for the calculations later.

$width_dif = $old_width - MAX_WIDTH;
$height_dif = $old_height - MAX_HEIGHT;

That should do the trick. Now, to determine which difference is great, we need to set a variable to tell us for our calculations:

if ($height_dif > $width_dif) { $max_dif = 'height'; }
else { $max_dif = 'width'; }

Okay, now that we have that determined it's time to do the meat of the function (or code block, whatever you're using it for):

if ($max_dif == 'width') {
$new_width = MAX_WIDTH;
$percentage = $new_width/$old_width;
$new_height = $old_height*$percentage;
} // End if ($max_dif == 'width')
elseif ($max_dif == 'height') {
$new_height = MAX_HEIGHT;
$percentage = $new_height/$old_height;
$new_width = $old_width*$percentage;
} // End if ($max_dif == 'height')

Basically, these calculations help the image to keep its proportions. It won't get resized to a fixed size, instead, it will be resized proportionally to keep the relative size of the objects in the image.

Now, let's return a pretty piece of HTML for the user to see:
return '<img src="' . $img_src . '" width="' . $new_width . '" height="' . $new_height . '">' . '<br />';

That should be it. If you'd like to see the full function that I wrote for this tutorial you can visit it at www.mustywindows.com/docs/resize_image.php

If you'd like to test out it's functionality you can install it on your site or go to the forums of www.mustywindows.com/mb and post a large picture. I have had it implimented on my forums for quite some time.

Well, enjoy!


None

keifer121

Reply To Post Reply & Quote

Posted at: 12/22/05 11:07 PM

keifer121 EVIL LEVEL 07

Sign-Up: 08/31/05

Posts: 400

good tutorial i might use it...

to tired to do it toay lo, maybe in a month if i remember

None

Drake-SI

Reply To Post Reply & Quote

Posted at: 12/23/05 08:31 AM

Drake-SI EVIL LEVEL 21

Sign-Up: 03/07/05

Posts: 609

Nice job, as always. I may use this sometime if I do make a portal as I plan to.


None

EviLDoG

Reply To Post Reply & Quote

Posted at: 12/23/05 09:06 AM

EviLDoG LIGHT LEVEL 12

Sign-Up: 10/18/00

Posts: 4,589

I made one in javascript for remote images... it could probably be shortened but it does the job.

<script type="text/javascript" language="javascript">
/*
Anime-Refuge Image rescaler script - Written by Deano
*/
function resizeImage (imageOrImageName, width, height) {
var image = typeof imageOrImageName == 'string' ?
document[imageOrImageName] : imageOrImageName;

if (document.layers) {
image.currentWidth = width;
image.currentHeight = height;
var layerWidth = image.width > width ? image.width : width;
var layerHeight = image.height > height ? image.height : height;
if (!image.overLayer) {
var l = image.overLayer = new Layer(layerWidth);
}
var l = image.overLayer;
l.bgColor = document.bgColor;
l.clip.width = layerWidth;
l.clip.height = layerHeight;
l.left = image.x;
l.top = image.y;
var html = '';
html += '<img src="' + image.src + '"';
html += image.name ? ' NAME="overLayer' + image.name + '"' : '';
html += ' width="' + width + '" height="' + height + '">';
l.document.open();
l.document.write(html);
l.document.close();
l.visibility = 'show';
}
else {
if (image.width > width || image.height > height) {
var wscale = width/image.width;
var hscale = height/image.height;
if (wscale<hscale) var scale = wscale;
else var scale = hscale;
var neww = image.width*scale;
var newh = image.height*scale;
image.width = neww;
image.height = newh;
}
}
}
</script>

Then all you do to output an image is:
<img src="filename.jpg" onLoad="resizeImage(this,100,100)">
Arguments:
<img src="filename of image" onLoad="resizeImage(javascript ref to the image,maximum width,maximum height)">

Great tutorial though! To let some of you know aswell, you can use the getimagesize() function on flash aswell, but this may not work with all animations and php versions.


None

Sir-Davey

Reply To Post Reply & Quote

Posted at: 12/23/05 10:36 AM

Sir-Davey FAB LEVEL 19

Sign-Up: 07/09/01

Posts: 3,093

I was hoping it would use the GD library :(. Good tutorial nonetheless.

BBS Signature

None

AlternateAccount

Reply To Post Reply & Quote

Posted at: 12/23/05 01:34 PM

AlternateAccount LIGHT LEVEL 14

Sign-Up: 06/21/03

Posts: 736

At 12/23/05 10:36 AM, Sir-Davey wrote: I was hoping it would use the GD library :(. Good tutorial nonetheless.

Yeah, but not many servers come with run it on default and unfortuantly, for most of the newgrounder's of whom are stuck on shared hosting; to set it up is an impossibility. Good tutorial though, I remember you explaining this to me way back and its a pretty interesting idea.


None

Pilot-Doofy

Reply To Post Reply & Quote

Posted at: 12/24/05 10:24 AM

Pilot-Doofy NEUTRAL LEVEL 37

Sign-Up: 09/13/03

Posts: 12,275

At 12/23/05 10:36 AM, Sir-Davey wrote: I was hoping it would use the GD library :(. Good tutorial nonetheless.

I've used GD a lot for my server, with custom sigs for users and stuff but I didn't want to post code using the GD library due to the compatibility issues.


None

fuzz

Reply To Post Reply & Quote

Posted at: 2/14/06 02:27 PM

fuzz NEUTRAL LEVEL 21

Sign-Up: 06/02/04

Posts: 5,647

Thanks! this will be perfect for my site, once i learn a bit of php!


None

Pilot-Doofy

Reply To Post Reply & Quote

Posted at: 2/14/06 09:42 PM

Pilot-Doofy NEUTRAL LEVEL 37

Sign-Up: 09/13/03

Posts: 12,275

At 2/14/06 02:27 PM, -fuzz- wrote: Thanks! this will be perfect for my site, once i learn a bit of php!

I created a new version, it really helps because you can show the image with no problems (hopefully since the document root is extracted from the source for linking) and you can edit the max height/width directly from the argument list.

function resize_image($img, $max_x=650, $max_y=650, $width=NULL, $height=NULL) {
$img_src = str_replace($_SERVER['DOCUMENT_ROOT'], '', $img);
# Note: This is only used on the Mustywindows.com server. It replaces the
# DOCUMENT ROOT path from the returned image HTML.

# Handle error checking
if (!is_string($img))
die('Fatal Error: Supplied argument is not a valid resource for resize_image.');
if (empty($img))
die('Fatal Error: No supplied argument for resize_image.');

# Get percentage of shrink
$dimensions = getimagesize($img);
$filename = basename($img); // returning this is optional

$old_width = $dimensions[0];
$old_height = $dimensions[1];

if ($old_width <= $max_x && $old_height <= $max_y) {
return '<img src="' . $img_src . '" width="' . $old_width . '" height="' . $old_height . '" alt="Image not altered by resizing">';
} # End error check for normal sized pictures

$width_dif = $old_width - $max_x;
$height_dif = $old_height - $max_y;

if ($height_dif > $width_dif) { $max_dif = 'height'; }
else { $max_dif = 'width'; }

if ($max_dif == 'width') {
$new_width = $max_x;
$percentage = $new_width/$old_width;
$new_height = $old_height*$percentage;
} // End if ($max_dif == 'width')
elseif ($max_dif == 'height') {
$new_height = $max_y;
$percentage = $new_height/$old_height;
$new_width = $old_width*$percentage;
} // End if ($max_dif == 'height')

# The new height and width were just defined in the
# above code blocks.

if ($width !== NULL) { $new_width = $width; }
if ($height !== NULL) { $new_height = $height; }

$alt_text = "File name: " . $filename . " - " .
"Original size: " . $old_width . "x" . $old_height . " - New size: " . $new_width . "x" . $new_height;

## Return material
return '<img alt="' . $alt_text . '" src="' . $img_src . '" width="' . $new_width . '" height="' . $new_height . '">';// . '<br />[a href="' . $img_src . '" target="_blank"]<font size="-2">Click here to view full size image!</font>[/a]';

} # End function


All times are Eastern Standard Time (GMT -5) | Current Time: 02:02 AM

<< Back

This topic is 1 page long.

<< < > >>
You need a Grounds Gold Account to post on the NG BBS! If you don't have one, click here to sign up now! It's fast, free, and easy — and opens up tons of great NG features!