Image upload script + thumbnail

Discussion in 'PHP' started by webmasterplace, Jan 9, 2008.

  1. #1
    Hi,

    I'm already looking for a long time now to get a special script. There are the functions that the script must have:

    • Upload an image (jpg or gif) and save it to an images folder on my server.
    • As soon as the image has been uploaded, there must be a thumbnail created (120x90) of that picture and saved into the images/thumbs folder.
    • Optional: The image name and thumbnail name must be saved into my MySQL database (just as text so I can simple call back the names in my other script).
    If someone can help me with a script like this, please post it here! I really need this, but can't make it myself :(
    If you have an uploadscript + thumbnail generator, but not with the MySQL function, then it's ok too. I'll try and figure it out myself then.

    Thank you very much!!
     
    webmasterplace, Jan 9, 2008 IP
  2. midhunhk

    midhunhk Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    ok dude, this is a small project that i did, i guess its just what you want. ill put up parts of the code so u can assemeble it, ok

    --Start php--
    // 4.2 Upload an image

    $uploadSuccess = false;
    $hasErrors = false;
    $message = "";
    $sImagePath = "";
    $showUploadForm = true;

    if($_POST["action"] == "Upload Image")
    {
    // get album name from album id
    $albumName = "";
    $sql = "SELECT * FROM gallery_album WHERE albid = '".$_POST['in_album']."'";
    $res = mysql_query($sql,$con);
    if($res){
    $row = mysql_fetch_row($res);
    $albumName = $row[1];
    }
    $albumPath = "albums/$albumName/"; // replace with the folder u need
    $thumbPath = $albumPath."thumbs/"; // thumbnail directory

    unset($imagename);

    if(!isset($_FILES) && isset($HTTP_POST_FILES)) $_FILES = $HTTP_POST_FILES;
    if(!isset($_FILES['image_file'])) $error["image_file"] = "An image was not found.";

    $imagename = basename($_FILES['image_file']['name']);
    // echo $imagename;

    if(empty($imagename)) $error["imagename"] = "The name of the image was not found.";

    if(empty($error))
    {
    switch($_FILES["image_file"]["type"])
    {
    case "image/png" :
    case "image/x-png": $source = imagecreatefrompng($_FILES["image_file"]["tmp_name"]); break;
    case "image/jpeg" :
    case "image/pjpeg": $source = imagecreatefromjpeg($_FILES["image_file"]["tmp_name"]); break;
    case "image/gif" : $source = imagecreatefromgif($_FILES["image_file"]["tmp_name"]); break;
    }

    $newimage = $albumPath.$imagename;
    $result = @move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
    if(empty($result))
    $error["result"] = "There was an error moving the uploaded file.";
    else
    {
    // success
    $sql = "INSERT INTO `album_image` (`parent_album` , `image_title` )VALUES ('".$_POST["in_album"]
    ."', '".basename($_FILES["image_file"]["name"])."');";

    $res = mysql_query($sql,$con);

    if($res) $uploadSucess = true;
    else {$hasErrors = true; $message = "Error Uploading the image";}
    }

    // Create Thumbnail
    //
    switch($_FILES["image_file"]["type"])
    {
    case "image/png" :
    case "image/x-png": $src_img = imagecreatefrompng($albumPath.basename($_FILES["image_file"]["name"])); break;
    case "image/jpeg" :
    case "image/pjpeg": $src_img = imagecreatefromjpeg($albumPath.basename($_FILES["image_file"]["name"])); break;
    case "image/gif" : $src_img = imagecreatefromgif($albumPath.basename($_FILES["image_file"]["name"])); break;
    }
    // $src_img = imagecreatefromjpeg($albumPath.basename($_FILES["image_file"]["name"]));
    $maxWidth = 150;
    $maxHeight = 150;

    list($width, $height, $type, $attr)=getimagesize($albumPath.basename($_FILES["image_file"]["name"]));
    $xRatio = $maxWidth / $width;
    $yRatio = $maxHeight / $height;
    if ( ($width <= $maxWidth) && ($height <= $maxHeight) ) {
    $newwidth = $width;
    $newheight = $height;
    }
    else if (($xRatio * $height) < $maxHeight) {
    $newheight = ceil($xRatio * $height);
    $newwidth = $maxWidth;
    }
    else {
    $newwidth = ceil($yRatio * $width);
    $newheight = $maxHeight;
    }

    $dst_img = imagecreate($newwidth,$newheight);
    imagecopyresized($dst_img,$src_img,0,0,0,0,$newwidth,$newheight,imagesx($src_img),imagesy($src_img));

    imagejpeg($dst_img, $thumbPath.basename($_FILES["image_file"]["name"]));
    //
    }


    -- end php --

    hope this is useful to you....
     
    midhunhk, Jan 9, 2008 IP
  3. webmasterplace

    webmasterplace Peon

    Messages:
    802
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you for your reply midhunhk!
    I'll try it out immediately :)
     
    webmasterplace, Jan 9, 2008 IP
  4. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #4
    Barti1987, Jan 9, 2008 IP
  5. webmasterplace

    webmasterplace Peon

    Messages:
    802
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #5
    webmasterplace, Jan 9, 2008 IP
  6. ausgezeichnete

    ausgezeichnete Peon

    Messages:
    54
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    this is one i use,its to update images from the database
    if u want to insert ,change only the sql statement to insert and
    $image_name=$row_Recordset1['home_img']; to
    $image_name=time().".jpg"; just to give the images name
    
    <?
    //define a maxim size for the uploaded images in Kb
     define ("MAX_SIZE","100"); 
    
    //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['Submit1'])) 
     {
     	//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) && ($size1 > MAX_SIZE*1024) && ($size2 > 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=$row_Recordset1['home_img'];
    
    //the new name will be containing the full path where will be stored (images folder)
    $newname=$image_name;
    
    //we verify if the image has been uploaded, and print error instead
    $copied = copy($_FILES['image']['tmp_name'], $newname);
    
    if (!$copied ) 
    {
    	echo '<h1>Copy unsuccessfull!</h1>';
    	$errors=1;
    }}}}
    
    //If no errors registred, print the success message
     if(isset($_POST['Submit1']) && !$errors) 
     {
     if($newname){
     ////////////////////insert into db////////
    			$conn=mysqli_connect("localhost","username","password","dbname");
    			$query=mysqli_query($conn,"update home set home_img='".$newname."'
    			 ");
    			if(!$query){echo "wrong".mysqli_error($conn);}else{echo " ";}
    			//////////////////////////////////////////////////////////////////
     	echo "<h1>File Uploaded Successfully! </h1>";
    	echo "These are the photos links:<br />";
    echo "Photo1:</h3><img src=$newname heigth=100 width=150/><br />";
    
    
    }else{echo "<i>Please Insert a Photo</i>";}
     }
    
     ?>
    
    <form name="newad" method="post" enctype="multipart/form-data"  action="" >
     <table align="center">
     <th>Upload Image </th>
     	<tr><td><input type="file" name="image">
     	<input name="Submit1" type="submit" value="Upload image"></td></tr>
     </table>	
     </form>
    
    
    PHP:
     
    ausgezeichnete, Jan 9, 2008 IP