Log in

View Full Version : Image Resizing



jfreak53
07-22-2009, 01:48 AM
How do I check the width of an image and height is and if either one is over a certain amount set the width or height of the <img src to that certain amount in restraints?

Thanks in advance.

Keleth
07-22-2009, 04:30 AM
I forget where I found this code, but here ya go:



$validMIMETypes = array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png');
$validExtensions = array('jpg', 'jpeg', 'gif', 'png');

if ($_FILES['picture']['error'] == 0 && $_FILES['picture']['size'] > 153600) { $_SESSION['errors']['picSizeError'] = TRUE; }
elseif ($_FILES['picture']['error'] == 0 && !in_array($_FILES['picture']['type'], $validMIMETypes)) { $_SESSION['errors']['picTypeError']; }
elseif ($_FILES['picture']['error'] == 0) {
$fileNameParts = explode('.',$_FILES['picture']['name']);
$extension = $fileNameParts[sizeof($fileNameParts) - 1];
$filename = $optionID.'.'.$extension;
move_uploaded_file($_FILES['picture']['tmp_name'], FILEROOT.'/uploads/positionOptions/'.$filename);

$source = FILEROOT.'/uploads/positionOptions/'.$filename;
$destination = FILEROOT.'/uploads/positionOptions/'.$filename;
$maxWidth = 120;
$maxHeight = 120;

list($imgWidth, $imgHeight, $imgType) = getimagesize($source);
if (image_type_to_mime_type($imgType) == 'image/jpeg' || image_type_to_mime_type($imgType) == 'image/pjpeg') { $tempImg = imagecreatefromjpeg($source); }
elseif (image_type_to_mime_type($imgType) == 'image/gif') { $tempImg = imagecreatefromgif($source); }
elseif (image_type_to_mime_type($imgType) == 'image/png') { $tempImg = imagecreatefrompng($source); }

$xRatio = $maxWidth / $imgWidth;
$yRatio = $maxHeight / $imgHeight;

if ($imgWidth <= $maxWidth && $imgHeight <= $maxHeight) {
$finalWidth = $imgWidth;
$finalHeight = $imgHeight;
} elseif (($xRatio * $imgHeight) < $maxHeight) {
$finalWidth = $maxWidth;
$finalHeight = ceil($xRatio * $imgHeight);
} else {
$finalWidth = ceil($yRatio * $imgWidth);
$finalHeight = $maxHeight;
}

$tempColor = imagecreatetruecolor($finalWidth, $finalHeight);
imagecopyresampled($tempColor, $tempImg, 0, 0, 0, 0, $finalWidth, $finalHeight, $imgWidth, $imgHeight);

if ($extension == 'jpg' || $extension == 'jpeg') { imagejpeg($tempColor, $destination, 100); }
elseif ($extension == 'gif') { imagegif($tempColor, $destination); }
elseif ($extension == 'png') { imagepng($tempColor, $destination); }
imagedestroy($tempImg);
imagedestroy($tempColor);

foreach ($validExtensions as $value) { if ($extension != $value) {
unlink(FILEROOT.'/uploads/positionOptions/'.$ballotOID.'.'.$value);
} }
}

jfreak53
07-22-2009, 02:52 PM
Thanks for the help. I'll test it out.

jfreak53
07-24-2009, 08:21 PM
After a little tweaking for my exact needs it works perfectly, thanks for the help.