views:

39

answers:

1

Hi

I am looking for a solution to upload an image, check the resolution crop it if necessary then then preview the image before it then gets printed onto a canvas.

I have found loads of examples of this but obviously nothing straight forward, plus i don't want to rip off someone elses work.

ASP is NOT an option as the site uses PHP and is on a 'nix box.

Any pointers would be much appreciated.

+1  A: 

Basically the file will need to be POSTed to your PHP script. You can do this with HTML forms(input type='file') or jQuery background uploaders. Uploads are stored by default in the temporary directory of your web server, the current directory can be found by looking at the output of phpinfo().

Next check out the $_FILES global specifically move_uploaded_file(), you can find the image type from the type key in the $_FILES array, though that can be manipulated client side it it might be better to check the file type manually using magic byte functions.

Once you have the file uploaded then you need to manipulate it. You can use either GD or ImageMagick, ImageMagick may not be built-in to your PHP version, GD is pretty common. I am more familar with GD, so I'll suggest you check out the functions imagecreatefromjpeg()/png/gif & imagecopyresampled(), which can both crop and resample. To find out if you need to crop / resize you can check the aspect ratio. Here's a function I whipped up:

function fixRatio($x, $y, $ratio) {
    $ratio = round($ratio,6);
    $iRatio = round($x / $y, 6);
    if ($iRatio > $ratio) {
        $x = ceil($y * $ratio);
    } else if ($iRatio < $ratio) {
        $y = ceil($x * (1 / $ratio));
    }
    return array('x' => $x, 'y' => $y);
}

You input the width, height & desired aspect ratio & this will spit out an array that contains the corrected dimensions. It's probably best to specify the ratio by dividing desired height by desired width, e.g. fixRatio($x, $y, 640/480). You can then use that info to crop the image w/ imagecopyresampled(), at the same time you can specify to the function the destination width & height. So if everything must be 640x480, then you would specify that when calling imagecopyresampled(). You can then use iamgejpeg()/gif/png to output the image as a file to a public directory on your server. Since it's public you can reference it via a URL be it an HTML form asking the user to confirm if they like what they see or into a canvas element.

Klinky