SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Zealot
    Join Date
    Feb 2006
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Upload image to multiple folders

    I'm uploading an image, but I want it to go to two different folders, in one folder the image will be the regular size which is 700 pixels wide and in the other folder will just be a thumbnail which will be 100 pixels.

    I can get it to add the image to the database as well as upload it to the first folder, but I can't get it to upload to the thumbnail folder too.

    This is what I've got, but I'm site sure where it's going wrong:
    Code:
    $style = (isset($_POST['style']) ? implode(' ', $_POST['style']) : '');
    //create array to temporarily grab variables
    $input_arr = array();
    //grabs the $_POST variables and adds slashes
    foreach ($_POST as $key => $input_arr) {
        $_POST[$key] = addslashes($input_arr);
    }
    
    // resizes an image to fit a given width in pixels.
    // works with BMP, PNG, JPEG, and GIF
    // $file is overwritten
    function fit_image_file_to_width($file, $w, $mime = 'image/jpeg') {
        list($width, $height) = getimagesize($file);
        $newwidth = $w;
        $newheight = $w * $height / $width;
    
        switch ($mime) {
            case 'image/jpeg':
                $src = imagecreatefromjpeg($file);
                break;
            case 'image/png';
                $src = imagecreatefrompng($file);
                break;
            case 'image/bmp';
                $src = imagecreatefromwbmp($file);
                break;
            case 'image/gif';
                $src = imagecreatefromgif($file);
                break;
        }
    
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
        switch ($mime) {
            case 'image/jpeg':
                imagejpeg($dst, $file);
                break;
            case 'image/png';
                imagealphablending($dst, false);
                imagesavealpha($dst, true);
                imagepng($dst, $file);
                break;
            case 'image/bmp';
                imagewbmp($dst, $file);
                break;
            case 'image/gif';
                imagegif($dst, $file);
                break;
        }
    
        imagedestroy($dst);
    }
    
    // init file vars
    $pic  = $_FILES['photo']['name'];
    $target = '/uploads/image/filename/thumb/' . basename( $_FILES['photo']['name']);
    $temp_name = $_FILES['photo']['tmp_name'];
    $type = $_FILES["photo"]["type"];
    $pic2  = $_FILES['photo']['name'];
    $target2 = '/uploads/image/filename/thumb/thumbnailbig/' . basename( $_FILES['photo']['name']);
    $temp_name2 = $_FILES['photo']['tmp_name'];
    $type2 = $_FILES["photo"]["type"];
    
    // Connects to your Database
    mysql_connect($host,$username,$password) or die(mysql_error()) ;
    mysql_select_db($database) or die(mysql_error()) ;
    
    // get form data
    $class = $_POST['class'];
    $foreign_id = $_POST['foreign_id'];
    $name = mysql_real_escape_string(isset($_POST['name']) ? $_POST['name'] : 'No name');
    $order = $_POST['order'];
    
    //Writes the information to the database
    mysql_query("INSERT INTO `images` (`id`, `class`, `foreign_id`, `title`, `filename`, `created`, `modified`, `order`, `category`) VALUES (NULL, '$_POST[class]', '$_POST[foreign_id]', '$_POST[name]', '$pic', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '$_POST[order]', '$style')");
    
    // resize the image in the tmp directorys
    fit_image_file_to_width($temp_name, 700, $type);
    fit_image_file_to_width($temp_name2, 100, $type2);
    
    //Writes the photo to the server
    if(move_uploaded_file($temp_name, $target))
    if(move_uploaded_file($temp_name2, $target2))

  2. #2
    SitePoint Addict FizixRichard's Avatar
    Join Date
    May 2003
    Location
    UK
    Posts
    372
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Copy the image from the first folder, resize it using an imaging library (i.e. GD) and copy it into the second thumbnail folder.
    FIZIX - Full Service Digital Agency - Engaging websites, apps and games.
    Follow us @FIZIXAgency

  3. #3
    SitePoint Zealot
    Join Date
    Feb 2006
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry to ask a dumb question but how do I do that? I'm very new to this and don't really know how to do that? What I've got so far allows somebody to upload an image of any size and it's then resized the 700 pixels, but I also want it to be resized to 100 pixels and put in the other folder.

  4. #4
    SitePoint Addict FizixRichard's Avatar
    Join Date
    May 2003
    Location
    UK
    Posts
    372
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    OK, I've got a general imaging class that can be used for resizing, copying and cropping. I've cut it down quite a bit, it should work as is and is commented. If you understand PHP you *should* understand it.

    It is fairly straight forward. We handle security separately, on upload and on a per case basis so be aware that this has limited security and I've cut it down for simplicity sakes.

    Code:
    <?php
    class image
    {
    	// ---------------------------------------------------------------------------------------------------
    	// Properties
    	// ---------------------------------------------------------------------------------------------------
    	private $preferences = array();			// Holds preferences	
    	private $scale;
    	
    
    
    	// ---------------------------------------------------------------------------------------------------
    	// __construct()
    	// --------------------------------------------------------------------------------------------------- 
    	// Constructor
    	//
    	// Pass prefs into class
    	// ---------------------------------------------------------------------------------------------------
    	function __construct($prefs) 
    	{			
    		// Set the preferences	
    		if (count($prefs) > 0)
    		{
    			$this->initialize($prefs);
    		}	
    		
    		return 0;	
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// initialize()
    	// --------------------------------------------------------------------------------------------------- 
    	// Initialize the image managemer
    	//
    	// @param prefs array				Array containing preferences
    	// ---------------------------------------------------------------------------------------------------
    	function initialize($prefs = array())
    	{
    		// Grab the default preferences
    		$default = $this->fetchDefaultPrefs();
    		
    		
    		// Overwrite defaults with supplied prefs
    		foreach($default as $key => $val)
    		{
    			if(isset($prefs[$key]))
    			{
    				// Set to supplied preference
    				$this->preferences[$key] = $prefs[$key];
    			}
    			else
    			{
    				// Set to default preference
    				$this->preferences[$key] = $val;
    			}
    		}
    		
    		return 0;
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// setPrefs()
    	// --------------------------------------------------------------------------------------------------- 
    	// Sets preferences to preferences array
    	//
    	// @param prefs array				Array containing preferences
    	// ---------------------------------------------------------------------------------------------------
    	function setPrefs($prefs = array())
    	{		
    		if (count($prefs) == 0)
    		{
    			echo('No preferences have been passed to the image library.');
    		}		
    		
    		
    		// Set the preferences
    		foreach($prefs as $key => $val)
    		{
    			if(isset($this->preferences[$key]))
    			{
    				// Set to supplied preference
    				$this->preferences[$key] = $prefs[$key];
    			}
    			else
    			{
    				// Set to default preference
    				$this->preferences[$key] = $val;
    			}
    		}
    	
    		
    		return 0;
    
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// resizeImage()
    	// --------------------------------------------------------------------------------------------------- 
    	// Method to resize images
    	// ---------------------------------------------------------------------------------------------------
    	public function resizeImage($prefs)
    	{		
    		// Set the preferences
    		$this->setPrefs($prefs);
    					
    		
    		// Check that the source image exists
    		$this->checkSourceImage();	
    		
    		
    		// Get the information for the source image
    		$width = $this->getWidth($this->preferences['sourcepath']);
    		$height = $this->getHeight($this->preferences['sourcepath']);
    		$aspect_ratio = $this->getAspectRatio($width, $height);
    		$mimetype = $this->getMimeType($this->preferences['sourcepath']);
    		
    		
    		// Figure out the new width and height
    		$new = $this->calculateNewDimensions($aspect_ratio, $width, $height);
    		
    		$newwidth = $new['width'];
    		$newheight = $new['height'];
    			
    		// Set the output method (so you can save as file or output as an image for viewing
    		if(empty($this->preferences['output']))
    		{
    			$this->preferences['output'] = 'file';
    		}
    				
    		
    		// Handle resizing using the GD or GD2 Library
    		if($this->preferences['imagelib'] == 'gd' || $this->preferences['imagelib'] == 'gd2')
    		{
    			$this->gdResizeImage($width, $height, $newwidth, $newheight, $mimetype, $this->preferences['output']);
    		}
    		else
    		{
    			// Could support other libs
    		}
    		
    		return 0;
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    		
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// gdResizeImage()
    	// --------------------------------------------------------------------------------------------------- 
    	// Method to resize or crop images using gd and gd2 libraries
    	// ---------------------------------------------------------------------------------------------------
    	public function gdResizeImage($width, $height, $newwidth, $newheight, $mimetype, $output='file')
    	{
    		if($output != 'file' && $output != 'screen')
    		{
    			$output = 'file';
    		}
    		
    		
    		// Figure out our create and copy functions
    		if($this->preferences['imagelib'] == 'gd2' && function_exists('imagecreatetruecolor'))
    		{
    			$create	= 'imagecreatetruecolor';
    			$copy	= 'imagecopyresampled';
    		}
    		else
    		{
    			$create	= 'imagecreate';
    			$copy	= 'imagecopyresized';
    		}
    		
    		
    		// Figure out read function
    		if($mimetype == "image/pjpeg" || $mimetype == "image/jpeg" || $mimetype == "image/jpg")
    		{
    			$suffix = "jpeg";
    			$quality = $this->preferences['quality'];
    			
    		}
    		if($mimetype == "image/gif")
    		{
    			$suffix = "gif";
    			$quality = $this->preferences['quality'];
    		}
    		if($mimetype == "image/png" || $mimetype == "image/x-png")
    		{
    			$suffix = "png";
    			$quality = $this->preferences['quality'] / 10;
    		}
    		
    		// Set the read/write GD functions
    		$read = 'imagecreatefrom' . $suffix; 
    		$write = 'image' . $suffix;
    		
    		
    				
    		
    		// Set x and y (for cropping)
    		if($this->preferences['crop'] == false)
    		{
    			$x = 0;
    			$y = 0;
    		}
    		else
    		{
    			$ratio = $width / $height;
    			
    			$x = $this->preferences['crop_x'];
    			$y = $this->preferences['crop_y'];
    			
    			if(empty($x))
    			{
    				$x = 0;
    			}
    			if(empty($y))
    			{
    				$y = 0;
    			}
    			
    			if($width > $this->preferences['maxwidth'])
    			{
    				$scale = $this->preferences['maxwidth'] / $width;
    			}
    			else
    			{
    				$scale = 1;
    			}	
    		
    		
    			$width = ceil($width * $scale);
    			$height = ceil($height * $scale);
    			
    		}
    		
    		
    		$src_handle = $read($this->preferences['sourcepath']); 
    		
    		if($src_handle == false)
    		{
    			echo('Source Image does not exist.');
    		}
    		
    		
    		
    		// Handle screen output
    		if($output == 'screen')
    		{
    			header('Content-Type: image/jpg');
        		header('Content-Disposition: inline; filename="'.basename($this->preferences['sourcepath']).'"');	
    			$tmpname = "";
    			
    			$temp = $create($newwidth, $newheight);
        		$copy($temp, $src_handle, 0, 0, $x, $y, $newwidth, $newheight, $width, $height);
       			$write($temp, $tmpname, $quality);
    		}
    		
    		
    		
    		// Handle file output (write new image)
    		if($output == 'file')
    		{
    			// Create the destination image
    			$destination_handle = $create($newwidth, $newheight);
    		
    		
    			// Preserve transparency for PNG images
    			if($mimetype == 'image/png' || $mimetype == 'image/x-png')
    			{
    				imagealphablending($destination_handle, false);
    				imagesavealpha($destination_handle, true);
    			}
    				
    			
    			// Copy the image
    			$copy($destination_handle, $src_handle, 0, 0, $x, $y, $newwidth, $newheight, $width, $height);
    			
    			
    			// Write the new image
    			$write($destination_handle, $this->preferences['newpath'], $quality);
    			
    			
    			//  Kill the handles
    			imagedestroy($destination_handle);
    			imagedestroy($src_handle);
    		}
    		
    		
    		return 0;
    	}
    	
    	
    
    	
    
    	
    	// ---------------------------------------------------------------------------------------------------
    	// checkSourceImage()
    	// --------------------------------------------------------------------------------------------------- 
    	// Checks to ensure the source image exists
    	// ---------------------------------------------------------------------------------------------------
    	public function checkSourceImage()
    	{
    		if(!file_exists($this->preferences['sourcepath']))
    		{
    			echo('Source file does not exist.');
    		}
    		else
    		{
    			return true;
    		}
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// getWidth()
    	// --------------------------------------------------------------------------------------------------- 
    	// Returns the width of the supplied image
    	// ---------------------------------------------------------------------------------------------------
    	public function getWidth($path)
    	{		
    		$size = getimagesize($path);
    		$width = $size[0];
    		
    		return $width;
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// getHeight()
    	// --------------------------------------------------------------------------------------------------- 
    	// Returns the height of the supplied image
    	// ---------------------------------------------------------------------------------------------------
    	public function getHeight($path)
    	{
    		$size = getimagesize($path);
    		$height = $size[1];
    		
    		return $height;
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// getAspectRatio()
    	// --------------------------------------------------------------------------------------------------- 
    	// Returns the aspect ratio of the supplied image (based on width and height)
    	// ---------------------------------------------------------------------------------------------------
    	public function getAspectRatio($width, $height)
    	{
    		// Image is square
    		if($height == $width)
    		{
    			$aspect_ratio = "square";
    		}
    		
    		// Image is landscape
    		if($width > $height)
    		{
    			$aspect_ratio = "landscape";
    		}
    		
    		// Image is portrait
    		if($height > $width)
    		{
    			$aspect_ratio = "portrait";
    		}
    		
    		return $aspect_ratio;
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// getMimeType()
    	// --------------------------------------------------------------------------------------------------- 
    	// Returns the mimetype of the supplied image
    	// ---------------------------------------------------------------------------------------------------
    	public function getMimeType($path)
    	{
    		$data = getimagesize($path);
    		$mimetype = $data['mime'];
    		return $mimetype;
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// calculateNewDimensions()
    	// --------------------------------------------------------------------------------------------------- 
    	// Returns the new dimensions of an image
    	// ---------------------------------------------------------------------------------------------------
    	public function calculateNewDimensions($aspect_ratio, $width, $height)
    	{
    		$maxwidth = $this->preferences['maxwidth'];
    		$maxheight = $this->preferences['maxheight'];
    		
    		
    		// Fixed Size Scaling fixes the size of the image (no aspect ratio scaling)
    		if($this->preferences['fixedsize'] == true)
    		{
    			if($this->preferences['fixedsize_mode'] == 'downscale')
    			{
    				if($width > $maxwidth)
    				{
    					$dimensions['width'] = $maxwidth;
    				}
    				
    				if($height > $maxheight)
    				{
    					$dimensions['height'] = $maxheight;
    				}
    			}
    			else
    			{
    				$dimensions['width'] = $maxwidth;
    				$dimensions['height'] = $maxheight;
    			}
    			
    			return $dimensions;
    		}
    		
    		
    		
    		
    		// Set for square images
    		if($aspect_ratio == "square")
    		{
    			if($width > $maxwidth)
    			{
    				$dimensions['width'] = $maxwidth;
    				$dimensions['height'] = $maxwidth;
    			}
    			else
    			{
    				$dimensions['width'] = $width;
    				$dimensions['height'] = $height;
    			}
    			
    			return $dimensions;
    		}
    		
    		
    		// For landscape images
    		if($aspect_ratio == "landscape")
    		{
    			if($width > $maxwidth)
    			{
    				$dimensions['width'] = $maxwidth;
    			}
    			else
    			{
    				$dimensions['width'] = $width;
    			}
    			
    			$ratio = $height / $width; 			
    			$dimensions['height'] = ceil($dimensions['width'] * $ratio);
    			
    			return $dimensions;
    		}
    		
    		
    		// For portrait images
    		if($aspect_ratio == "portrait")
    		{
    			if($height > $maxheight)
    			{
    				$dimensions['height'] = $maxheight;
    			}
    			else
    			{
    				$dimensions['height'] = $height;
    			}
    			
    			$ratio = $width / $height; 			
    			$dimensions['width'] = ceil($dimensions['height'] * $ratio);
    			
    			return $dimensions;			
    		}
    		
    				
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    	
    	// ---------------------------------------------------------------------------------------------------
    	// fetchDefaultPrefs()
    	// --------------------------------------------------------------------------------------------------- 
    	// Fetches default imaging preferences
    	// ---------------------------------------------------------------------------------------------------
    	private function fetchDefaultPrefs()
    	{
    		$prefs = array(
    							'haltonerror'			=> true,				// Whether to halt on errors
    							'imagelib'				=> 'gd2',				// Library to use (gd, gd2)
    							'librarypath'			=> '',					// Path to the image library							
    							'sourcepath'			=> ''					// Path to the source image
    		);
    								
    		return $prefs;
    	}
    	// ---------------------------------------------------------------------------------------------------
    	
    	
    	
    }
    ?>

    To use the class (simplest way possible):

    Code:
    require('class_imaging.php');
    
    // Perform upload (putting image into a source folder (original image)
    ...
    
    // Set preferences (prefs are optional)
    $prefs = array(
    	'sourcepath'	=>	PATH_TO_SOURCE_IMAGE							
    );
    		
    		
    // Instantiate the imge manager
    $imageManager = new image($prefs);
    
    
    // Lets try to create a thumbnail
    // -------------------------------------------------------------------------------------------------------			
    $prefs = array(
    							'sourcepath'				=>	PATH_TO_SOURCE_IMAGE,
    							'newpath'					=> 	PATH_TO_THUMBNAIL_IMAGE,	
    							'maxwidth'					=>	'300',
    							'maxheight'					=>	'300',
    							'fixedsize'					=>	false,
    							'fixedsize_mode'			=> 	'',
    							'quality'					=>	'90'		
    );
    
    $imageManager->resizeImage($prefs);

    Of course you could do this twice;

    1. Grab source image, scale image to fit fullsize requirements
    2. Grab source image, scale to thumbnail requirements

    Then you can either keep or delete the source image.

    You could even use the output option so that you could just have the source image and create a script that scales and displays the image and instead of doing:

    Code:
    <img src="theimage.jpg">
    Do
    Code:
    <img src="image.php?id=theimage">

    * note, this code is not perfect, just simple.


    ETA:
    You pass preferences to the class when you instantiate it, then call the relevant method.


    Resizing is as above; cropping would be:
    Code:
    $prefs = array(
    							'sourcepath'				=>	sourceimage,
    							'newpath'					=> 	outputimage,	
    							'maxwidth'					=>	'800',
    							'maxheight'					=>	'800',
    							'fixedsize'					=>	false,
    							'fixedsize_mode'			=> 	'',
    							'quality'					=>	'90',
    							'crop'						=>	'true',
    							'crop_x'					=>	'200',
    							'crop_y'					=>	'0'				
    			);
    FIZIX - Full Service Digital Agency - Engaging websites, apps and games.
    Follow us @FIZIXAgency

  5. #5
    SitePoint Zealot
    Join Date
    Feb 2006
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you, I'll have a look at that and try adding it, just a couple of questions though. 1) Do I still need the code I've got to add the filename to the database? 2) where do I specify the folder names?

    Thank you so much for your help though

  6. #6
    SitePoint Addict FizixRichard's Avatar
    Join Date
    May 2003
    Location
    UK
    Posts
    372
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Well you will still need to perform the initial image upload; so lets say you have a form with a file browse element; you will still need to grab that file and upload it to a folder. For example "source_images"; which will contain the original source images; you would perform your security and validation at that point.

    You will need to figure out your naming and such. It's a multi-purpose class; so its like a base; you need to specify site specific functionality yourself; like adding an entry to the DB; paths, naming conventions and such).

    To specify the paths:

    Code:
    $prefs = array(
    							'sourcepath'				=>	PATH_TO_SOURCE_IMAGE,
    							'newpath'					=> 	PATH_TO_THUMBNAIL_IMAGE,	
    							'maxwidth'					=>	'300',
    							'maxheight'					=>	'300',
    							'fixedsize'					=>	false,
    							'fixedsize_mode'			=> 	'',
    							'quality'					=>	'90'		
    );
    
    $imageManager->resizeImage($prefs);
    Look at the preferences array:

    sourcepath: This is the path to the source image you upload (in the source_images folder from my first paragraph)
    newpath: This is the path where the resized image will go; i.e. "thumb_images/imagename.jpg"
    maxwidth: This is the maximum width for the imege
    maxheight: This is the maximum height for the image
    fixedheight and fixedsize_mode: Ignore these
    quality: Thats the quality of the final image

    You can use the class to scale any image to whatever parameters you need; so for thumbs, cover images or whatever; so you can use it anywhere, for anything.
    FIZIX - Full Service Digital Agency - Engaging websites, apps and games.
    Follow us @FIZIXAgency

  7. #7
    SitePoint Zealot
    Join Date
    Feb 2006
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks I'll give it a go

  8. #8
    SitePoint Addict FizixRichard's Avatar
    Join Date
    May 2003
    Location
    UK
    Posts
    372
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    No problem; it is a class from our framework; I pulled a few bits out that are dependent upon the framework and changed the error output system calls to "echo"'s, as the framework itself would bog you down.

    There shouldn't be any errors but if there are, just say here and I'll help.
    FIZIX - Full Service Digital Agency - Engaging websites, apps and games.
    Follow us @FIZIXAgency

  9. #9
    SitePoint Zealot
    Join Date
    Feb 2006
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay I've tried it but just got a whole load of errors. This is what I got:

    Source file does not exist.
    Warning: getimagesize(/app/webroot/uploads/image/filename/$pic) [function.getimagesize]: failed to open stream: No such file or directory in /app/webroot/new_site/includes/class_imaging.php on line 340

    Warning: getimagesize(/app/webroot/uploads/image/filename/$pic) [function.getimagesize]: failed to open stream: No such file or directory in /app/webroot/new_site/includes/class_imaging.php on line 357

    Warning: getimagesize(/app/webroot/uploads/image/filename/$pic) [function.getimagesize]: failed to open stream: No such file or directory in /app/webroot/new_site/includes/class_imaging.php on line 406

    Fatal error: Call to undefined function imagecreatefrom() in /app/webroot/new_site/includes/class_imaging.php on line 252

    These lines are:

    340:
    Code:
    	$size = getimagesize($path);
    357:
    Code:
    	$size = getimagesize($path);
    406:
    Code:
    	$data = getimagesize($path);
    252:
    Code:
    	$src_handle = $read($this->preferences['sourcepath']);
    I've also changed the array so that it's now this:
    Code:
    $prefs = array(
    							'sourcepath'				=>	'/app/webroot/uploads/image/filename/$pic',
    							'newpath'					=> 	'/app/webroot/uploads/image/filename/thumb/thumbnailbig/$pic',	
    							'maxwidth'					=>	'100',
    							'maxheight'					=>	'100',
    							'fixedsize'					=>	false,
    							'fixedsize_mode'			=> 	'',
    							'quality'					=>	'90'		
    );
    $pic is suppose the be the filename of the file that's just been uploaded

    My entire code is now:
    Code:
    require('../includes/class_imaging.php');
    include '../includes/meta.php';
    include '../includes/db.php';
    $style = (isset($_POST['style']) ? implode(' ', $_POST['style']) : '');
    //create array to temporarily grab variables
    $input_arr = array();
    //grabs the $_POST variables and adds slashes
    foreach ($_POST as $key => $input_arr) {
        $_POST[$key] = addslashes($input_arr);
    }
    
    // resizes an image to fit a given width in pixels.
    // works with BMP, PNG, JPEG, and GIF
    // $file is overwritten
    function fit_image_file_to_width($file, $w, $mime = 'image/jpeg') {
        list($width, $height) = getimagesize($file);
        $newwidth = $w;
        $newheight = $w * $height / $width;
    
        switch ($mime) {
            case 'image/jpeg':
                $src = imagecreatefromjpeg($file);
                break;
            case 'image/png';
                $src = imagecreatefrompng($file);
                break;
            case 'image/bmp';
                $src = imagecreatefromwbmp($file);
                break;
            case 'image/gif';
                $src = imagecreatefromgif($file);
                break;
        }
    
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
        switch ($mime) {
            case 'image/jpeg':
                imagejpeg($dst, $file);
                break;
            case 'image/png';
                imagealphablending($dst, false);
                imagesavealpha($dst, true);
                imagepng($dst, $file);
                break;
            case 'image/bmp';
                imagewbmp($dst, $file);
                break;
            case 'image/gif';
                imagegif($dst, $file);
                break;
        }
    
        imagedestroy($dst);
    }
    
    // init file vars
    $pic  = $_FILES['photo']['name'];
    $target = '/app/webroot/uploads/image/filename/' . basename( $_FILES['photo']['name']);
    $temp_name = $_FILES['photo']['tmp_name'];
    $type = $_FILES["photo"]["type"];
    
    // Connects to your Database 
     mysql_connect($host,$username,$password) or die(mysql_error()) ; 
     mysql_select_db($database) or die(mysql_error()) ;
    
    // get form data
    $class = $_POST['class'];
    $foreign_id = $_POST['foreign_id'];
    $name = mysql_real_escape_string(isset($_POST['name']) ? $_POST['name'] : 'No name');
    $order = $_POST['order'];
    
    //Writes the information to the database 
    mysql_query("INSERT INTO `images` (`id`, `class`, `foreign_id`, `title`, `filename`, `created`, `modified`, `order`, `category`) VALUES (NULL, '$_POST[class]', '$_POST[foreign_id]', '$_POST[name]', '$pic', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '$_POST[order]', '$style')"); 
    
    // resize the image in the tmp directorys
    fit_image_file_to_width($temp_name, 700, $type);
    
    //Writes the photo to the server
    if(move_uploaded_file($temp_name, $target))
    
    // Set preferences (prefs are optional)
    $prefs = array(
    	'sourcepath'	=>	PATH_TO_SOURCE_IMAGE							
    );
    		
    		
    // Instantiate the imge manager
    $imageManager = new image($prefs);
    
    
    // Lets try to create a thumbnail
    // -------------------------------------------------------------------------------------------------------			
    $prefs = array(
    							'sourcepath'				=>	'/app/webroot/uploads/image/filename/$pic',
    							'newpath'					=> 	'/app/webroot/uploads/image/filename/thumb/thumbnailbig/$pic',	
    							'maxwidth'					=>	'100',
    							'maxheight'					=>	'100',
    							'fixedsize'					=>	false,
    							'fixedsize_mode'			=> 	'',
    							'quality'					=>	'90'		
    );
    
    $imageManager->resizeImage($prefs);

  10. #10
    SitePoint Addict FizixRichard's Avatar
    Join Date
    May 2003
    Location
    UK
    Posts
    372
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Ah...

    First; we have a file management class, so we verify that the file uploaded correctly and that it's safe at that point, the image manager isn't used for verification of the files existence on upload.

    Secondly:

    Code:
    'sourcepath' => '/app/webroot/uploads/image/filename/$pic',
    'newpath' => '/app/webroot/uploads/image/filename/thumb/thumbnailbig/$pic',
    ' quotes are literal; so it's literally looking for /app/webroot/uploads/image/filename/$pic (so a filename called $pic). The error message tells you that if you look; it's looking for an image called $pic. Where as " quotes will parse variables.


    So if you were to do:

    $welcometext = 'Welcome $username';

    the $welcome text would contain "Welcome $username"


    Whereas if you did:
    $welcometext = 'Welcome ' . $username;
    - or -
    $welcometext = "Welcome $username";

    It would show the correct text.


    You need to either:

    Code:
    'sourcepath' => '/app/webroot/uploads/image/filename/' . $pic,
    'newpath' => '/app/webroot/uploads/image/filename/thumb/thumbnailbig/' . $pic,
    Or

    Code:
    'sourcepath' => "/app/webroot/uploads/image/filename/$pic",
    'newpath' => "/app/webroot/uploads/image/filename/thumb/thumbnailbig/$pic",
    Preferably the former.
    FIZIX - Full Service Digital Agency - Engaging websites, apps and games.
    Follow us @FIZIXAgency

  11. #11
    SitePoint Zealot
    Join Date
    Feb 2006
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay I think we're getting somewhere with this, I've just tested it and it kind of works, if I upload jpg, gif or png files it works, but if I upload JPG, GIF or PNG files (ie if the extension is in capitals) it doesn't work? Maybe I've got something wrong but that seems pretty strange to me?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •