Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Advance Image upload & Resizing 1

Status
Not open for further replies.

WilliamMute007

Programmer
Sep 30, 2007
116
GB
Hi All,

I have a script which basically uploades an image to folder (unique folder) each time.

I wanted to extend this script so that when it uploads the image, it should ALSO create a small thumbnail of it so I'll have the original and a small version. I want to store the two images in the same folder with the smaller one simply having "small" or something of that nature appended to the end of the original file name so I can distinguish the two.

The main script works perfectly but I have been having problems for over a day now with the resizing. Please see if you can help... Script below


Code:
<?
include('verify.php');


$title = $_POST['title'];
$text = $_POST['text'];
$categorie = $_POST['categorie'];
$categorie_name = $_POST['categorie_name'];
$author = $_POST['author'];

// Call for the name of categorie
$queryd = "SELECT * FROM $table_d WHERE id_cat=$categorie"; 
$resultd = mysql_query($queryd);
$mycat = @mysql_fetch_object($resultd);
$categorie_name = $mycat->categorie_name;

// LAST INCREMENTATION
$queryz = "SELECT last FROM $table_g"; 
$resultz = mysql_query($queryz);
$incr = @mysql_fetch_object($resultz);
$nrowss = $incr->last;

// NEW ID
$id= $nrowss+1;

umask(0000);
mkdir('../appreciateduploads/'.$id.'', 0777);
	// Folder blog + id of the new article
	$uploadDir = '../appreciateduploads/'.$id.'/';
	
	// Image file data
	$fileName = $_FILES['preview']['name'];
	$tmpName  = $_FILES['preview']['tmp_name'];

    // File extension extraction
	$ext = substr(strrchr($fileName, "."), 1);
	
	// File extension verification
	if ($ext != "jpg" ) { 
		echo ("Only jpg file are accepted (extension .jpg) Thanks !");
		exit;
		}

		
	// Generate random name
	$randName = md5(rand() * time());
	
	// Creation of path
    $filePath = $uploadDir . $fileName;
    $newfilename = $fileName;




list($width,$height)=getimagesize($tmpName, $filePath);
$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=150; //This is where I set the width of the thumbnail
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,

 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 

$width,$height);


$filename = "../"$filePath"/". $_FILES['preview']['name'];
$filename1 = "../"$filePath"small". $_FILES['preview']['name'];


//$filename = "upload/". $_FILES['file']['name']; //This is where I decide where to store the original image.  Same size as the thumb
$filename1 = ($tmpName,$filePath ["small"]);
//imagejpeg($tmp,$filename,100);
imagejpeg($tmpName,$filename1,100);
		





    // UPLOAD IMAGE
	// If something wrong.... we stop ! or we upload.
    $result    = move_uploaded_file($tmpName, $filename1, $filePath);
	if (!$result) {
		echo "Error during upload... Please try again or request assistant.";
		exit;
	}







$date_post	=	date("Y-m-d H:i:s");

$insert = mysql_query("INSERT INTO $table_b 
                       (
					   title,
					   text,
					   preview,
					   categorie,
					   categorie_name,
					   author,
					   date_post
					   )
					   VALUES
					   (
					   '$title',
					   '$text',
					   '$newfilename',
					   '$categorie',
					   '$categorie_name',
					   '$author',
					   '$date_post'
					   )") or die(mysql_error()); 
if(!$insert) echo alert("Error during insert...");

$update = mysql_query("UPDATE $table_g SET last='$id'");

if(!$update) echo alert("Error during update...");

header("location:update_rss.php");
?>


I appreciate your help in advance please.

Thank you
 
No worries, I understand you have your hands full and I appreciate your help. Here is the error am now getting with the changes suggested:


Array ( [0] => 1600 [1] => 1200 [2] => 2 [3] => width="1600" height="1200" [bits] => 8 [channels] => 3 [mime] => image/jpeg )
Warning: unlink(/tmp/image_14c8a7b39e09a6.jpeg) [function.unlink]: No such file or directory in /home/fhlinux132/m/mmakers.co.uk/user/htdocs/Template/PHP_/CMS/blog_add_process_new.php on line 66

Warning: implode() [function.implode]: Argument must be an array in /home/fhlinux132/m/mmakers.co.uk/user/htdocs/Template/PHP_/CMS/blog_add_process_new.php on line 74
Cannot insert table data Column count doesn't match value count at row 1
 
i have no way to test this without setting up the html form and the database etc, but i think i have ironed out the warnings and bugs

Code:
<?php
    include('verify.php');
    //make sure that we actually have a file to work with
    if ($_FILES['preview']['error'] !== 0):
        exit('There was an error with the upload');
    endif;
    
    $title = $_POST['title'];
    $text = $_POST['text'];
    $categorie = $_POST['categorie'];
    $categorie_name = $_POST['categorie_name'];
    $author = $_POST['author'];
    
    // Call for the name of categorie
    $queryd = "SELECT * FROM $table_d WHERE id_cat=" . intval(mysql_real_escape_string($categorie)); 
    $resultd = mysql_query($queryd);
    $mycat = @mysql_fetch_object($resultd);
    $categorie_name = $mycat->categorie_name;
    
    // LAST INCREMENTATION
    $queryz = "SELECT last FROM $table_g"; 
    $resultz = mysql_query($queryz);
    $incr = @mysql_fetch_object($resultz);
    $nrowss = intval($incr->last);
    
    // NEW ID
    
    $id= $nrowss++;
    
    //make sure that we are looking at a fresh directory
    while (is_dir('../appreciateduploads/'.$id)):
        $id++;
    endwhile;
    
    //get the proper path of the directory
    $uploadDir = realpath('../appreciateduploads');
    $uploadDir .= DIRECTORY_SEPARATOR . $id;
    
    //create directory
    $u = umask(0000);
    mkdir($uploadDir, 0777);
    
    //reset umask
    umask($u);
    
    // Image file data
    $fileName = $_FILES['preview']['name'];
    $tmpName  = $_FILES['preview']['tmp_name'];
    
    // Creation of path
    $preview = $newFileName = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
      
    //get information about the image

    list($width,$height, $type)=getimagesize($tmpName);
    switch ($type):
        //support png and jpeg
        CASE IMAGETYPE_JPEG:
        CASE IMAGETYPE_PNG:
            $thumb = makeThumbnail($tmpName, 60);
            if ($thumb):
                move_uploaded_file($tmpName, $fileName);
                rename($thumb, $uploadDir . DIRECTORY_SEPARATOR . 'thumb_' . $fileName);
                //clear up if necessary
                clearstatcache();
				if (is_file($thumb)):
                    @unlink($thumb);
                endif;
                
                //update the database
                $date_post    =    date("Y-m-d H:i:s");
                //create an array for easy manipulation
                $data = compact ('title','text','preview','categorie','categorie_name','author','date_post');
                $data = array_map('mysql_real_escape_string', $data);
                $query = "Insert into $table_b (" . implode(',', array_keys($data)) . ") VALUES ('".implode(',',array_values($data)) . "')";
                mysql_query($query) or die('Cannot insert table data ' . mysql_error());
                
                //update the counter
                mysql_query("UPDATE $table_g SET last='$id'") or die('Cannot update counter ' . mysql_error());
                
                //redirect
                header("location:update_rss.php");
                exit;
            else:
                exit('error in creating thumbnail');
            endif;
        break;
        default:
            exit('File type is not supported');
    endswitch;        

function makeThumbnail($image, $width){
    if (!is_file($image)) return false;
    $info = getimagesize($image);
   // print_r($info);
    list($oldwidth, $oldheight, $type) = $info; 
    $suffix = strtolower(image_type_to_extension($type, false));
    $height = intval(($width/$oldwidth) * $oldheight);
    
    //get image type and create some variable functions
    $cF = 'imagecreatefrom'.$suffix;
    $sF = 'image'.$suffix;
    $qM = $suffix == 'jpeg' ? 100 : 9;
    
    //instantiate image
    $img = $cF($image);
    
    //instantiate new image
    $nImg = imagecreatetruecolor($width, $height);
    //resize image
    imagecopyresampled($nImg, $img, 0,0,0,0,0,0,$oldWidth, $oldHeight);
    imagedestroy($img);
    $fN = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('image_'. true) . '.' . $suffix;
    $result = $sF($nImg, $fN, $qM);
    imagedestroy($nImg);
    return $result ? $fN : false;
}
?>
 
Thanks for that, Here is the error:

"Cannot insert table data Column count doesn't match value count at row 1"

 
can you add
Code:
echo $query;

just before the mysql_query() line for the input query please?
 
Here you go sir!

Insert into mm_appreciated (title,text,preview,categorie,categorie_name,author,date_post) VALUES ('Test Name,I am the text for the body,/home/fhlinux132/m/mmakers.co.uk/user/htdocs/Template/PHP_/appreciateduploads/16/Picture 005.jpg,2,Consultant,Position of Person,2010-09-10 22:45:09')Cannot insert table data Column count doesn't match value count at row 1
 
easy one this time
Code:
<?php
    include('verify.php');
    //make sure that we actually have a file to work with
    if ($_FILES['preview']['error'] !== 0):
        exit('There was an error with the upload');
    endif;
    
    $title = $_POST['title'];
    $text = $_POST['text'];
    $categorie = $_POST['categorie'];
    $categorie_name = $_POST['categorie_name'];
    $author = $_POST['author'];
    
    // Call for the name of categorie
    $queryd = "SELECT * FROM $table_d WHERE id_cat=" . intval(mysql_real_escape_string($categorie)); 
    $resultd = mysql_query($queryd);
    $mycat = @mysql_fetch_object($resultd);
    $categorie_name = $mycat->categorie_name;
    
    // LAST INCREMENTATION
    $queryz = "SELECT last FROM $table_g"; 
    $resultz = mysql_query($queryz);
    $incr = @mysql_fetch_object($resultz);
    $nrowss = intval($incr->last);
    
    // NEW ID
    
    $id= $nrowss++;
    
    //make sure that we are looking at a fresh directory
    while (is_dir('../appreciateduploads/'.$id)):
        $id++;
    endwhile;
    
    //get the proper path of the directory
    $uploadDir = realpath('../appreciateduploads');
    $uploadDir .= DIRECTORY_SEPARATOR . $id;
    
    //create directory
    $u = umask(0000);
    mkdir($uploadDir, 0777);
    
    //reset umask
    umask($u);
    
    // Image file data
    $fileName = $_FILES['preview']['name'];
    $tmpName  = $_FILES['preview']['tmp_name'];
    
    // Creation of path
    $preview = $newFileName = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
      
    //get information about the image

    list($width,$height, $type)=getimagesize($tmpName);
    switch ($type):
        //support png and jpeg
        CASE IMAGETYPE_JPEG:
        CASE IMAGETYPE_PNG:
            $thumb = makeThumbnail($tmpName, 60);
            if ($thumb):
                move_uploaded_file($tmpName, $fileName);
                rename($thumb, $uploadDir . DIRECTORY_SEPARATOR . 'thumb_' . $fileName);
                //clear up if necessary
                clearstatcache();
				if (is_file($thumb)):
                    @unlink($thumb);
                endif;
                
                //update the database
                $date_post    =    date("Y-m-d H:i:s");
                //create an array for easy manipulation
                $data = compact ('title','text','preview','categorie','categorie_name','author','date_post');
                $data = array_map('mysql_real_escape_string', $data);
                $query = "Insert into $table_b (" . implode(',', array_keys($data)) . ") VALUES ('".implode('\',\',array_values($data)) . "')";
                mysql_query($query) or die('Cannot insert table data ' . mysql_error());
                
                //update the counter
                mysql_query("UPDATE $table_g SET last='$id'") or die('Cannot update counter ' . mysql_error());
                
                //redirect
                header("location:update_rss.php");
                exit;
            else:
                exit('error in creating thumbnail');
            endif;
        break;
        default:
            exit('File type is not supported');
    endswitch;        

function makeThumbnail($image, $width){
    if (!is_file($image)) return false;
    $info = getimagesize($image);
   // print_r($info);
    list($oldwidth, $oldheight, $type) = $info; 
    $suffix = strtolower(image_type_to_extension($type, false));
    $height = intval(($width/$oldwidth) * $oldheight);
    
    //get image type and create some variable functions
    $cF = 'imagecreatefrom'.$suffix;
    $sF = 'image'.$suffix;
    $qM = $suffix == 'jpeg' ? 100 : 9;
    
    //instantiate image
    $img = $cF($image);
    
    //instantiate new image
    $nImg = imagecreatetruecolor($width, $height);
    //resize image
    imagecopyresampled($nImg, $img, 0,0,0,0,0,0,$oldWidth, $oldHeight);
    imagedestroy($img);
    $fN = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('image_'. true) . '.' . $suffix;
    $result = $sF($nImg, $fN, $qM);
    imagedestroy($nImg);
    return $result ? $fN : false;
}
?>
 
Here is the Error:

Parse error: syntax error, unexpected '"' in /home/fhlinux132/m/mmakers.co.uk/user/htdocs/Template/PHP_/CMS/blog_add_process_new.php on line 75
 
no syntax error on my side. are you sure that you have copied and pasted ok?

maybe change the quotes in the $query line
Code:
                $query = "Insert 
							into $table_b 
							(" . implode(',', array_keys($data)) . ") 
							VALUES 
							('".implode("','", array_values($data)) . "')";
 
You are right Justin, it was the query string, works now BUT I've just checked on my MySQL DB and the table row "preview" is being populated with the following

"/home/fhlinux132/m/mmakers.co.uk/user/htdocs/Template/PHP_/appreciateduploads/16/Picture 005.jpg"

As the image path, this is surely not right is it? When I call the image on the page it doesnt display

Also, The upload folder for each record only contain the thumb_picture$id not both files, i.e the original uploaded file plus thumbnail in one folder rather than just the risized.


I really appreciate your help as I know you are very busy


Thank you!
 
1. yes - the whole path would get included. when serving the file via an image tag you either need to use relative uri's, translate to a url or use an image server. i would go for the last.
to go for the first change this line
Code:
$uploadDir = [s]realpath[/s]('../appreciateduploads');
note that this will only ever work if the page you are visiting is one folder down from appreciateduploads.

If you want to go down the path translation route i can probably provide a translation script. something like this might work
Code:
function translateAbsoluteToRelative($filename){
		$bits= pathinfo($filename);
		$docRoot = $_SERVER['DOCUMENT_ROOT'];
		$dir = str_replace($docRoot, '', $bits['dirname']);
		return '[URL unfurl="true"]http://'[/URL] . $_SERVER['SERVER_ADDR'] . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $bits['basename'];
}

an image server is a bit more complex but more secure.

to get the uri of the thumbnail rather than the main file use this function

Code:
	function getThumb($filename, $prefix = 'thumb_'){
		$bits = pathinfo($filename);
		$file = $bits['dirname'] . DIRECTORY_SEPARATOR . $prefix . $bits['basename'];
		return $file;
	}
2. the move_uploaded_file is incorrect. use this line instead
Code:
 move_uploaded_file($tmpName, $uploadDir . DIRECTORY_SEPARATOR .$fileName);
 
Justin, Thank you so much! you made my day. I appreciate all your input. It works now. As for the image uri, I think I'll stick with the simple option lol, been on this for 2 days now and I am way behind. You have also been on it most of today so I don't want to prolong it.

I really really appreciate all your help, THANK YOU!
 
My pleasure

I may post a proper image server script as an FAQ next week. There are better ways than using the gd extension and it so stones makes sense to specify the desired size in the request rather than creating it as a cache up front.

Have a good weekend


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top