Be a Supporter!

PHP: resizing and copying images

  • 1,579 Views
  • 3 Replies
New Topic Respond to this Topic
Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
PHP: resizing and copying images 2006-07-18 22:09:38 Reply

In this tutorial, we'll learn how to write a function that will take an image, reduce it's dimensions with the GD library, then (in this tutorial) store the image. The function is easily editable to make the requested image outputted, but that method doesn't have as many uses as the storing method so we won't discuss it any further.

Before you continue, note that you will need the GD2 library installed on your server in order to follow this guide.

Without further space taking text, here is the function. We'll see how it works after you briefly skim it for its context.

function resize($filename, $max_width=200, $sendTo='/thumbnails/tmp.jpg') {

if ( !file_exists($file) )
return false;

$type = preg_replace('#.*?\.(.+)$#i', '\\1', $filename);

$path = $_SERVER['DOCUMENT_ROOT'] . $sendTo;
if ( !file_exists($path) ) {
$fp = @fopen($path, 'r+');
@chmod($path, 0777);
@fclose($fp);
}

if ( stristr($filename, '.jpg') ) {
$type = 'jpeg';
}

$func = 'imagecreatefrom' . $type;

// Content type
//header('Content-type: image/' . $type);

// Get new dimensions
list($width, $height) = getimagesize($filename);

# Calculate percent
$per = $width/$max_width;

$new_width = $max_width;
$new_height = $height / $per;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = $func($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, $path, 100);
return true;
} // End function

Firstly, let's look at the argument list. The $filename argument is self explanitory. This is the first argument and the only required one in the list. This should be the path on the remote server to the image you are wanting to edit.

The second argument is the max_width argument. If you're working with a site like myspace, and the max width of pictures is typically 90pixels, you could set the default value to this argument as 90. However, you can still manually specify it each time you call the function.

Lastly is the path to store the new image. If you're not going to be storing images and you're going to be outputting them to the browser, you won't need to teter with this argument. However, the path that is there will most likely not work on your remote server.

I've seen a few people request an argument change up as far as order when I've posted this function other places. For me in my personal uses, I'm constantly specifying the max width each time I call the function and I'm not always specifying the storage path, so the current setup works the best. But you can feel free to rearrange the optional arguments all your wish.

Now, let's see the processes in the function itself. First, of course, we check to see if the file being resized exists. If it doesn't, the function returns with a false value. Note, no matter what, as long as the file exists the function will return true. Assuming another error occurs, in most cases PHP will arise a fatal error to stop the script anyway.

Nextly, you should ensure that all the files being passed to the resize() function are images. If they are not of image type, then PHP will raise a fatal error when it calls "imagecreatefrom*" functions.

Then, we determine what type of image is being handled, and store the appropriate function name.

I have commented out a few lines of code that would cause the image to outputted to the browser instead of stored. This is for flexibility to those wanting to output the image.

Next, we calculate the new height for the image with the specified width. Note that if an image is smaller than the specified dimensions, it will be stretched. I have not included a very comprehensive returning system for this function, but it is still quite effective and fast.

Next, we store a blank image in the system memory using the imagecreatetruecolor() function. Once we have the image's memory set aside, we can copy the old image into the "dynamic clipboard" of the $image variable.

Then we use the imagecopyresampled() function, which does just that. It stores the contents of the old image with the new specified dimensions into the memory space we created with imagecreatetruecolor().

Once we have the code for our new image, we're ready to output or store it. In this case, we store it by specifying the second and optional argument of the imagejpeg() function. The third parameter is just the quality of the image, which I always set to 100 for best quality.

Now that we've looked at this function, you should note that it only allows for jpeg output. This is easiy changed. You could call the output function like this:

$outputFunc = 'image' . $type;
$outputFunc($image_p, $path);

I think you get the point. Well, that's the tutorial, hope you enjoyed it! If you have questions about customizing it just ask away and I'll answer them. This is just the source I use for a few sites of mine, so I didn't want to completely modify it but I'm happy to answer questions about it.

cherries
cherries
  • Member since: Jun. 7, 2005
  • Offline.
Forum Stats
Member
Level 18
Blank Slate
Response to PHP: resizing and copying images 2006-07-18 22:10:48 Reply

nice function :D
another great addition to PHP: Main

henke37
henke37
  • Member since: Sep. 10, 2004
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to PHP: resizing and copying images 2006-07-19 12:45:21 Reply

You got a logic flaw there, it will force it to have that width even if the width is the allowed width or smaller.
And it doesn't check wich side that is the bigest side.


Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.

Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to PHP: resizing and copying images 2006-07-19 20:11:18 Reply

At 7/19/06 12:45 PM, henke37 wrote: You got a logic flaw there, it will force it to have that width even if the width is the allowed width or smaller.

Yes, I addressed the stretching issues in the commentary.