greens85 Posted March 3, 2010 Share Posted March 3, 2010 Hi All, I currently have a script that allows me to upload an image and have it save to a directory on the server... however what I need to do is find someway to alter it so that the image is resized (kept in proportion) and then saved to a different directory e.g. thumbs. My current script is: <?php session_start(); //Check if the session is valid, if not return them to the login page if(!session_is_registered("candidate_username")){ header("location:../processcandidatelogin.php"); } //Include the connection to the database include ("dbconnection.php"); //Query the database for all details of the candidate $query = "SELECT * FROM edworld_candidates WHERE uname='$_SESSION[candidate_username]'"; $result = mysql_query($query) or die (mysql_error()); $row = mysql_fetch_array($result); $id = $row['id']; //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","2048"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); $query = "UPDATE edworld_candidates SET image = '$image_name' WHERE id = '$id'"; $result = mysql_query($query) or die (mysql_error()); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } ?> Can anyone advise? Many thanks, Greens85 Link to comment https://forums.phpfreaks.com/topic/193981-resizing-an-image-and-saving-it-as-a-thumb/ Share on other sites More sharing options...
AdRock Posted March 3, 2010 Share Posted March 3, 2010 There's loads of sample code forcreating thumbnails online http://www.plus2net.com/php_tutorial/php_thumbnail.php Link to comment https://forums.phpfreaks.com/topic/193981-resizing-an-image-and-saving-it-as-a-thumb/#findComment-1020825 Share on other sites More sharing options...
Dennis1986 Posted March 3, 2010 Share Posted March 3, 2010 http://snippets.dzone.com/posts/show/3843 Link to comment https://forums.phpfreaks.com/topic/193981-resizing-an-image-and-saving-it-as-a-thumb/#findComment-1020826 Share on other sites More sharing options...
ferdi Posted March 3, 2010 Share Posted March 3, 2010 I found this two function some time ago, I can't even remember from where. They've worked excellently for me, so here; function genimg($docroot, $new_file_location, $maxWidth=150, $maxHeight=150, $append='') { $size = GetImageSize($docroot . $new_file_location); $mime = $size['mime']; $width = $size[0]; $height = $size[1]; $offsetX = 0; $offsetY = 0; $xRatio = $maxWidth / $width; $yRatio = $maxHeight / $height; if ($xRatio * $height < $maxHeight){ $tnHeight = ceil($xRatio * $height); $tnWidth = $maxWidth; } else { $tnWidth = ceil($yRatio * $width); $tnHeight = $maxHeight; } $quality = 100; $dst = imagecreatetruecolor($tnWidth, $tnHeight); switch ($size['mime']) { case 'image/gif': $creationFunction = 'ImageCreateFromGif'; $outputFunction = 'ImageGif'; $mime = 'image/png'; // We need to convert GIFs to PNGs $doSharpen = FALSE; break; case 'image/png': $creationFunction = 'ImageCreateFromPng'; $outputFunction = 'ImagePng'; $doSharpen = FALSE; $quality = round(10 - ($quality / 10)); break; default: $creationFunction = 'ImageCreateFromJpeg'; $outputFunction = 'ImageJpeg'; $doSharpen = TRUE; break; } $src = $creationFunction($docroot . $new_file_location); if (in_array($size['mime'], array('image/gif', 'image/png'))) { if (!$color) { imagealphablending($dst, false); imagesavealpha($dst, true); } else { if ($color[0] == '#') $color = substr($color, 1); $background = FALSE; if (strlen($color) == 6) $background = imagecolorallocate($dst, hexdec($color[0].$color[1]), hexdec($color[2].$color[3]), hexdec($color[4].$color[5])); else if (strlen($color) == 3) $background = imagecolorallocate($dst, hexdec($color[0].$color[0]), hexdec($color[1].$color[1]), hexdec($color[2].$color[2])); if ($background) imagefill($dst, 0, 0, $background); } } ImageCopyResampled($dst, $src, 0, 0, $offsetX, $offsetY, $tnWidth, $tnHeight, $width, $height); if ($doSharpen) { $sharpness = findSharp($width, $tnWidth); $sharpenMatrix = array( array(-1, -2, -1), array(-2, $sharpness + 12, -2), array(-1, -2, -1) ); $divisor = $sharpness; $offset = 0; imageconvolution($dst, $sharpenMatrix, $divisor, $offset); } $outputFunction($dst, $docroot . $append . $new_file_location, $quality); ImageDestroy($src); ImageDestroy($dst); return array($width, $height); } function findSharp($orig, $final) { $final = $final * (750.0 / $orig); $a = 52; $b = -0.27810650887573124; $c = .00047337278106508946; $result = $a + $b * $final + $c * $final * $final; return max(round($result), 0); } Link to comment https://forums.phpfreaks.com/topic/193981-resizing-an-image-and-saving-it-as-a-thumb/#findComment-1020827 Share on other sites More sharing options...
greens85 Posted March 3, 2010 Author Share Posted March 3, 2010 Hey, Thanks for all the quick replies! @adrock With the example you posted, is the thumbnail actually saved? If it is I cant seem to see the line of code that does it? I can see it has a path and moves the file e.g. $add="upimg/".$_FILES[userfile][name]; // the path with the file name where the file will be stored, upload is the directory name. //echo $add; if(move_uploaded_file ($_FILES[userfile][tmp_name],$add)){ echo "Successfully uploaded the mage"; chmod("$add",0777); }else{echo "Failed to upload file Contact Site admin to fix the problem"; exit;} but is that the original its moving or the thumb??? @ferdi Again I can't see where the thumbnail is being saved maybe I am just overlooking the piece of code that does it! Link to comment https://forums.phpfreaks.com/topic/193981-resizing-an-image-and-saving-it-as-a-thumb/#findComment-1020832 Share on other sites More sharing options...
greens85 Posted March 3, 2010 Author Share Posted March 3, 2010 AdRock... Forget that, I've found the line! I was just overlooking it... I will give it a try now. Many thanks for the link! Link to comment https://forums.phpfreaks.com/topic/193981-resizing-an-image-and-saving-it-as-a-thumb/#findComment-1020834 Share on other sites More sharing options...
greens85 Posted March 3, 2010 Author Share Posted March 3, 2010 Hi again, I have tried customising my code, from the link but the thumbnail doesnt seem to be creating from the original image... can anyone advise? <?php session_start(); //Check if the session is valid, if not return them to the login page if(!session_is_registered("candidate_username")){ header("location:../processcandidatelogin.php"); } //Include the connection to the database include ("dbconnection.php"); //Query the database for all details of the candidate $query = "SELECT * FROM edworld_candidates WHERE uname='$_SESSION[candidate_username]'"; $result = mysql_query($query) or die (mysql_error()); $row = mysql_fetch_array($result); $id = $row['id']; //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","2048"); //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. //If the error occures the file will not be uploaded. $errors=0; //checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file //in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); $query = "UPDATE edworld_candidates SET image = '$image_name' WHERE id = '$id'"; $result = mysql_query($query) or die (mysql_error()); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } /////////////////////////// ADDED FROM HERE //////////////////////////////////////////////////////////////////// //Thumbnail Generation $n_width=100;//Fix Width $n_height=100; //Fix Height $tsrc = "images/thumbs/".$_FILES['image']['name']; // Path for image storage if(!($_FILES['image']['type'] == "image/pjpeg" || $_FILES['image']['type'] == "image/gif" || $_FILES['image']['type'] == "image/jpg" || $_FILES['image']['type'] == "image/jpeg" || $_FILES['image']['type'] == "image/png")) { echo "JPEG or GIF only"; exit; } // Create GIF Thumb // if (@$_FILES['image']['type'] == "image/gif") { $im = imagecreatefromgif ($copied); $width = imagesx($im); // Original Width $height = imagesy($im); // Original Height $newimage = imagecreatetruecolor ($n_width,$n_height); imagecopyresized($newimage, $im, 0,0,0,0,$n_width,$n_height,$width,$height); if (function_exists("imagegif")) { header("Content-type:image/gif"); imagegif($newimage, $tsrc); } elseif (function_exists("imagejpeg")) { header("Content-type:image/jpeg"); imagejpeg(£newimage, $tsrc); } chmod ("$tsrc", 0777); } // END CREATION // Create JPEG Thumb // if ($_FILES['image']['type'] == "image/jpg") { $im = imagecreatefromjpeg ($copied); $width = imagesx($im); // Original Width $height = imagesy($im); //Original Height $newimage = imagecreatetruecolor($n_width,$n_height); imagecopyresized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height); imagejpeg($newimage,$tsrc); chmod("$tsrc",0777); } // END CREATION /////////////////////////////////////////////////////////// TO HERE //////////////////////////////////////////////////////////////////// ?> Link to comment https://forums.phpfreaks.com/topic/193981-resizing-an-image-and-saving-it-as-a-thumb/#findComment-1020851 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.