Create thumbnail when uploaded

i am very very new to php and so far i have a website that creates thumbnails on the fly. ive been reading a few places and they say creating on the fly is a no no. i was wondering if someone could take thre time and help me change my code to create the thumbnails when uploaded and how to display them?

i have had a look at php.net and still dont understand how i would go about it.

here is the code to upload the image:

<?php
 
 $max_size=5*1024*1024;
 
 // Check if a file has been uploaded
if(isset($_FILES['uploaded_file']) && preg_match("/image\\/jpeg|image\\/jpg/i",$_FILES['uploaded_file']['type']) && $_FILES['uploaded_file']['size']<= $max_size)
{
     // Make sure the file was sent without errors
     if($_FILES['uploaded_file']['error'] == 0)
     {
         $target_path = "images/";
        $target_path = $target_path . basename( $_FILES['uploaded_file']['name']); 
        
        if(!file_exists($target_path)){

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path))
        {
            echo "The file ".  basename($_FILES['uploaded_file']['name']). " has been uploaded";
                                     
            $dbLink = new mysqli('localhost', 'root', '', 'gallery');
             if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
                                        }             
         
              // Gather all required data
              $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
              $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
              $size = intval($_FILES['uploaded_file']['size']);
              $image_path = $dbLink->real_escape_string($target_path);
              $gallery_type = $dbLink->real_escape_string($_POST['gallery_type']);
             $desc = $dbLink->real_escape_string($_POST['desc']);
             
             //query to insert the data i had gathered into the database
             $query = "INSERT INTO `images` (`name`, `size`, `created`, `image_path`, `gallery_type_id`, `desc` )
             VALUES ('{$name}', {$size}, NOW(), '{$image_path}', '{$gallery_type}', '{$desc}')";
             
             //executes the query
             $dbLink->query($query);
        }
    }
      
    else 
         {
            echo 'A file with the same name exists please change the file name and try again';
          }
}
  
  else
          {
      echo 'A file was not sent';
        }
}

else
          {
      echo 'The file is too large';
        }
        
 // Echo a link back to the main page
 echo '<p>Click <a href="member-index.php">here</a> to go back</p>'; 
 ?> 

and this is how i display my thumbanils now:

while ($row = $result->fetch_assoc()) {

echo "<a href=\\"image.php?id=" . $row['id'] . "\\">";
echo "<img src=\\"imageResize.php?imageFilename=" . $row['name'] . "&maxHeight=90&maxWidth=150\\" />\
";
echo "</a>\
";

The problem with creating the thumbnails on the fly is that it means you have to process them every time you access that URL.

The fix, in your case, is quite simple.

  1. Create a directory called Thumbnails or whatever takes your fancy
  2. In imageResize.php, first check if that filename exists in the thumbnails directory.
  3. If it doesn’t exist, create the image and save it into that thumbnails directory.
  4. Output the image using readfile() (and the appropriate headers, of course).

So it’d be, in pseudo:

$filename = sprintf('thumbs/%s', $_GET['imageFilename']);
if(!file_exists($filename)){
    //create thumbnail
    //save thumbnail to $filename
}
header('content-type: ...');
readfile($filename);

This also peeks into the power of mod_rewrite. I cache image files such as thumbnails where the webserver can “see” them. If they are present the image is sent out without PHP being started at all

If the image isn’t present PHP starts and examines the path. If it determines the thumbnail should exist it creates it, then outputs it to the webpath so that the next user loads the image without starting PHP (and incurring the overhead), then sends the image out to the user.

Typically though you’ll want to generate your thumbnails at the time of the upload, dodging most of this process. Joomla and Drupal each do this, hence the reason they need you to 777 certain directories (which isn’t entirely true, you just have to insure the webserver program has write privileges to the directory).

Also saunders, check your terms. A transmission from server to client is a DOWNload, not an UPload (which is a transmission from client to server).

the problem is. i would need to upload the file to my database. i want to upload a full sized image and a thumbnail. but wouldnt know how to go about it. i already upload a full sized image.

i know in words i need to.
1.upload image to folder
2. create thumbnail and upload that to thumbs folder
3. write the path of the images on the database in images table and do the same for in the thumbnail table.
4. display thumbnails

and with the knowledge of me coding very small i cant seem to work it out.

Assuming the first image isn’t huge PHP can resize it using an image library which is Usually compiled in. Here’s a class for working with the library I wrote a year or two ago.


<?php
class PAMWF_ImageHandler 
{
	protected $sourcePath = '';
	protected $image = null;
	protected $destination = null;
	protected $type = '';
	protected $currentHeight = 0;
	protected $currentWidth = 0;
	
	public function load( $file ) {
		$this->sourcePath = $file;
	
		if(empty($type)) {
			$type = strtolower(pathinfo($file, PATHINFO_EXTENSION));
		}
		
		$imageAttributes = getimagesize($this->sourcePath);
		$this->currentHeight = $imageAttributes[1];
		$this->currentWidth = $imageAttributes[0];
		
		switch ($imageAttributes['mime']) {
			case 'jpg':
			case 'jpeg':
			case 'image/jpeg':
				$this->type = 'jpeg';
				$this->image = @imagecreatefromjpeg($this->sourcePath);
			break;
			case 'png':
			case 'image/png':
				$this->type = 'png';
				$this->image = @imagecreatefrompng($this->sourcePath);
			break;
			case 'gif':
			case 'image/gif':
				$this->type = 'gif';
				$this->image = @imagecreatefromgif($this->sourcePath);
			break;
		}
		
		if (!$this->image) {
			throw new Exception('PHP was unable to load Image');
		}		
	}
	
	public function clear() {
		if (is_resource($this->image)) {
			imagedestroy($this->image);
		}
		
		if (is_resource($this->destination)) {
			imagedestroy($this->destination);
		}

		$this->sourcePath = '';
		$this->image = null;
		$this->destination = null;
		$this->type = '';
		$this->currentHeight = 0;
		$this->currentWidth = 0;	
	}
	
	public function resize( $targetHeight, $targetWidth, $trim = false, $secondPass = false ) {
		if ( ($targetHeight && $targetWidth ) && 
			($targetHeight <= $this->currentHeight || $targetWidth <= $this->currentWidth) 
		) {
			$heightRatio = $targetHeight / $this->currentHeight;
			$widthRatio = $targetWidth / $this->currentWidth;

			## If we are trimming we want the short side to fit to match it's target.
			## If we aren't trimming we want the long side to fit to it's target.
			$ratio = ($this->currentHeight >= $this->currentWidth && !$trim ) ? $heightRatio : $widthRatio;
			
			$newHeight = floor( $this->currentHeight * $ratio );
			$newWidth = floor( $this->currentWidth * $ratio );
	
			if ($secondPass) {
				$this->destination = imagecreatetruecolor( $targetWidth, $targetHeight );			
			} else {
				$this->destination = imagecreatetruecolor( $newWidth, $newHeight );		
			}
			
			imagecopyresampled(
				$this->destination, 
				$this->image,
				0, 0, 0, 0, // Coordinate settings are unused by this class. 
				$newWidth,
				$newHeight, 
				$this->currentWidth, 
				$this->currentHeight
			);
			
			$this->image = $this->destination;
			$this->destination = null;
			$this->currentHeight = $newHeight;
			$this->currentWidth = $newWidth;
			
			if (!$secondPass && $trim && ( $newHeight > $targetHeight || $newWidth > $targetWidth ) ) {
				$this->resize($targetHeight, $targetWidth, true, true );
			}
		}
	}
	
	public function save ( $path, $type = null, $compression = 100 ) {
		if (empty($type)) {
			$type = $this->type;
		}
		
		if (empty($compression)) {
			$compression = 100;
		}
		
		switch ($type) {
			case 'jpg':
			case 'jpeg':
			case 'image/jpeg':
				imagejpeg($this->image, $path, $compression);
			break;
			case 'png':
			case 'image/png':
				imagepng($this->image, $path);
			break;
			case 'gif':
			case 'image/gif':
				imagegif($this->image, $path);
			break;
		}
	}
}
?>

Basic usage of the class

<?php
$imageHandler = new PAMWF_ImageHandler();
$imageHandler->load($pathToFullSizeImage);
$imageHandler->resize( $height, $width, $type, $compression ); // compression only matters to jpg images
$imageHandler->save($outputPathForThumbnail);
?>

Tinker with it and have fun.

how would i use that with a upload form? cause i alreay use a file called add_file.php