
Feb 12th, 2008, 11:45
|
 |
SuperMember
|
|
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
|
Re: Automatic file size reduction
Okay here's a quick example using a file found in $_FILES['pic']..
The error handling is tack as it's only an example
- PHP: Select all
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$picH = '500'; // maxium height
$picW = '500'; // maximum width
// first we'll check this is a valid file and go from there
if (!is_uploaded_file($_FILES['pic']['tmp_name']))
die ('You\'re naughty! Don\'t try hack me!');
// okay so its a valid file let's get the extension
$ext = explode('.', $_FILES['pic']['name']);
$ext = strtolower($ext[count($ext)-1]);
//check if file type is okay...
if (!in_array($ext, $allowed))
die ('That file type is not allowed');
$ext = $ext == 'jpg' ? 'jpeg' : $ext; // need to turn jpg to jpeg for later.
// let's get the uploaded images dimensions
$dim = getimagesize($_FILES['pic']['tmp_name']); // gets an array of image dimenstions [0]= width [1] = height
// work by what percentage we would have to resize to for each
$ph = ceil(($picH / $dim[1]) * 100);
$pw = ceil(($picW / $dim[0]) * 100);
// okay, now, if the either dimension is greater than 100% of the allowed we need to recalculate
if ($ph > 100 || $pw > 100)
$rc = $pc = $pw > $ph ? $pw / 100 : $ph / 100; // take the largest percentage decrease
$width = ceil($dim[0] * $rc); // new width
$height = ceil($dim[1] * $rc); // new height
// get rid of our working variables
unset($ph, $pw);
// get the binary data from the old image
$func = 'imagecreatefrom' . $ext
$om = $func($_FILES['pic']['tmp_name']);
// create the new image
$im = imagecreatetruecolor($width, $height);
// now resample the old image into the new one based on our new width and height
$im = imagecopyresampled($im, $ol, 0,0,0,0, $width, $height, $dim[0], $dim[1]);
// now we'll store it ... as a jpg (but you can just replace imagejpg with image $ext
imagejpeg($im, 'C:/Path/to/where/you/want/' . $_FILES['pic']['name']);
}
I don't work with images too often but that's a quick look at how I would do it... I went pretty quickly so the maths is a bit chunky
Last Blog Entry: The wannabe juggler's quest (Oct 27th, 2007)
Last edited by Rakuli; Feb 12th, 2008 at 15:29.
Reason: syntax error in first and second ifs - and allowed
|