tags:

views:

51

answers:

3

Okay I'm really new to PHP I found the following script below. But i dont know how to use it I was wondering where do I put the link to the image for example images/photo.jpg inorder to get me started in learning this script thanks.

Here is the code.

<?php
function resizeImage($originalImage,$toWidth,$toHeight){

 // Get the original geometry and calculate scales
 list($width, $height) = getimagesize($originalImage);
 $xscale=$width/$toWidth;
 $yscale=$height/$toHeight;

 // Recalculate new size with default ratio
 if ($yscale>$xscale){
  $new_width = round($width * (1/$yscale));
  $new_height = round($height * (1/$yscale));
 }
 else {
  $new_width = round($width * (1/$xscale));
  $new_height = round($height * (1/$xscale));
 }

 // Resize the original image
 $imageResized = imagecreatetruecolor($new_width, $new_height);
 $imageTmp     = imagecreatefromjpeg ($originalImage);
 imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

 return $imageResized;
}
?>
A: 

You'd pass the link to the original JPEG as the first parameter in the function, which would be set as $originalImage.

So when calling the function, you'd use:

resizeImage("images/photo.jpg",800,600);

The two numbers would be your width/height values.

BraedenP
A: 

Instead of the return line you must add

header('Content-type: image/jpeg');
imagejpeg($imageResized);


Or check http://www.php.net/manual/en/function.imagejpeg.php and the Example #2 Saving a JPEG image

powtac
I wanna do more then save just a jpg image.
PeAk
Yes I understand, but the code is missing to either save or show the manipulated image!
powtac
imagejpeg($imageResized);returns the changed image to the browser!!!
powtac
+1  A: 

There are a couple of potential gotchas here, so I'll give you a few of the potential issues you can run into:

  1. You need to give the full path to the image so that it can be read. I use the following script for this:
function getRoot(){
    $cwd = getcwd();
    $splitCwd = explode("/", $cwd);
    $root = "";
    for($count=0; $count<count($splitCwd)-1;$count++){
      $root .= '/' . $splitCwd[$count];
    }
    $root = $root . '/';
    return $root;
}

Then you can pass in (getRoot() . $image, ...)

  1. Create a switch that will check the file type (see my answer here). This will allow you to resize more than just jpegs, and output more than just jpegs, which is good when transparency may be involved.

  2. There possible could be a final parameter or two, which is output filename. That way, you can make thumbnails while leaving the original image intact. In that case, you would do the imagejpeg (or imagepng, etc), and pass it the new name parameter if it is set.

Cryophallion