Results 1 to 7 of 7

Thread: Loading, resizing and renaming images

  1. #1
    Join Date
    Jun 2006
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Loading, resizing and renaming images

    Hi!
    I was hoping that someone could give some advice on altering this code. As it stands, it uploads a picture file, gives it a random name, resizes it then creates a thumbnail.

    I would like to alter this so that it can upload and resize image and thumbnail files separately. I would also like it to name the files using the $productId, such as $image = "i" . $productId . ".jpg".

    (Handling the sql results is done with an abstraction layer.)

    Here's what I got so far:
    function addProduct()
    {
    $catId = $_POST['cboCategory'];
    $name = $_POST['txtName'];
    $description = $_POST['mtxDescription'];
    $price = str_replace(',', '', (double)$_POST['txtPrice']);
    $qty = (int)$_POST['txtQty'];
    $sale = $_POST['cboSale'];
    $notes = $_POST['mtxNotes'];

    $images = uploadProductImage('fleImage', SRV_ROOT . 'images/');

    $mainImage = $images['image'];
    $thumbnail = $images['thumbnail'];

    $sql = "INSERT INTO tbl_product (cat_id, pd_name, pd_description, pd_price, pd_qty, pd_image, pd_thumbnail, pd_date, pd_sale, pd_notes)
    VALUES ('$catId', '$name', '$description', $price, $qty, '$mainImage', '$thumbnail', NOW(), '$sale', '$notes')";
    $result = dbQuery($sql);

    header("Location: index.php?catId=$catId");
    }

    //Upload an image and return the uploaded image name
    function uploadProductImage($inputName, $uploadDir)
    {
    $image = $_FILES[$inputName];
    $imagePath = '';
    $thumbnailPath = '';

    // if a file is given
    if (trim($image['tmp_name']) != '') {
    $ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

    // generate a random new file name to avoid name conflict
    $imagePath = md5(rand() * time()) . ".$ext";

    list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);

    // make sure the image width does not exceed the maximum allowed width
    if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
    $result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
    $imagePath = $result;
    } else {
    $result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
    }

    if ($result) {
    // create thumbnail
    $thumbnailPath = md5(rand() * time()) . ".$ext";
    $result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH);

    // create thumbnail failed, delete the image
    if (!$result) {
    unlink($uploadDir . $imagePath);
    $imagePath = $thumbnailPath = '';
    } else {
    $thumbnailPath = $result;
    }
    } else {
    // the product cannot be upload / resized
    $imagePath = $thumbnailPath = '';
    }
    }
    return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
    }

    //Create a thumbnail of $srcFile and save it to $destFile; The thumbnail will be $width pixels
    function createThumbnail($srcFile, $destFile, $width, $quality = 75)
    {
    $thumbnail = '';

    if (file_exists($srcFile) && isset($destFile))
    {
    $size = getimagesize($srcFile);
    $w = number_format($width, 0, ',', '');
    $h = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

    $thumbnail = copyImage($srcFile, $destFile, $w, $h, $quality);
    }

    // return the thumbnail file name on sucess or blank on fail
    return basename($thumbnail);
    }

    //copy an image to a destination file. The destination image size will be $w X $h pixels
    function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
    {
    $tmpSrc = pathinfo(strtolower($srcFile));
    $tmpDest = pathinfo(strtolower($destFile));
    $size = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
    $destFile = substr_replace($destFile, 'jpg', -3);
    $dest = imagecreatetruecolor($w, $h);
    imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
    $dest = imagecreatetruecolor($w, $h);
    imageantialias($dest, TRUE);
    } else {
    return false;
    }

    switch($size[2])
    {
    case 1: //GIF
    $src = imagecreatefromgif($srcFile);
    break;
    case 2: //JPEG
    $src = imagecreatefromjpeg($srcFile);
    break;
    case 3: //PNG
    $src = imagecreatefrompng($srcFile);
    break;
    default:
    return false;
    break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch($size[2])
    {
    case 1:
    case 2:
    imagejpeg($dest,$destFile, $quality);
    break;
    case 3:
    imagepng($dest,$destFile);
    }
    return $destFile;

    }

    Thanks in advance for any advice!
    Jacqui

  2. #2
    Join Date
    Feb 2008
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default height for images

    Hi

    how to resize height for images ?

  3. #3
    Join Date
    Feb 2008
    Location
    Cebu City Philippines
    Posts
    1,160
    Thanks
    17
    Thanked 277 Times in 275 Posts

    Default

    Hi lol33d,
    You should not hijack someone's thread, anyway, you can resize the height, as well as the width using CSS.It could be something like:
    <img src="image.jpg" style="height:300px;width:300px;">

    See if it helps
    Learn how to code at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph!

  4. #4
    Join Date
    Feb 2008
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    WOW! THANKS


    how to resize height for images ON [uploadProductImage] & [createThumbnail] FUNCTION PHP CODE

  5. #5
    Join Date
    Feb 2008
    Location
    Cebu City Philippines
    Posts
    1,160
    Thanks
    17
    Thanked 277 Times in 275 Posts

    Default

    ...and those are things that I don't know :lol:
    If I have to locate it in the PHP code above, I have this fear that I will lose a number of hair
    Learn how to code at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph!

  6. #6
    Join Date
    Aug 2007
    Location
    Ohio
    Posts
    79
    Thanks
    0
    Thanked 15 Times in 15 Posts

    Default

    Here's a simple PHP 5 class that can resize and save .gif, .png and .jpg files.

    Code:
    <?php
    
    class My_Image {
    
    	private $src, $im, $ext;
    	
    	public function __construct($filename) {
    		$this->src = $filename;
    		$this->loadFile();
    	}
    	
    	private function loadFile() {
    		$file = $this->src;
    		
    		$system=explode('.',$file);
    		if (preg_match('/jpg|jpeg/',strtolower(end($system)))){
    			$this->ext = array('jpeg','.jpg');
    			$this->im = imagecreatefromjpeg($file);
    		}
    		elseif (preg_match('/png/',strtolower(end($system)))){
    			$this->im = imagecreatefrompng($file);
    			$this->ext = array('png','.png');
    		}
    		elseif (preg_match('/gif/',strtolower(end($system)))) {
    			$this->im = imagecreatefromgif($file);
    			$this->ext = array('gif','.gif');
    		}
    		else {
    			// unsupported format
    			$this->im = false;
    			return false;
    		}
    		
    		return true;
    	}
    	
    	public function resize($maxwidth, $maxheight) {
    	
    		
    		list($width, $height, $type, $attr) = getimagesize($this->src);
    		
    		
    		if($width > $maxwidth OR $height > $maxheight) {
    		
    			// EXAMPLE SCENARIO
    			// Max-width: 700px, max-height: 400px
    			// width: 800px, max-height: 650px
    			// width ratio: .875   height ratio: .615
    			
    			$widthRatio = $maxwidth/$width;
    			$heightRatio = $maxheight/$height;
    		
    			if($widthRatio < $heightRatio) {
    				$new_width = $maxwidth;
    				$new_height = $height*$widthRatio;
    			}
    			elseif($heightRatio < $widthRatio) {
    				$new_height = $maxheight;
    				$new_width = $width*$heightRatio;
    			}
    			else {
    				$new_width = $width*$widthRatio;
    				$new_height = $height*$heightRatio;
    			}
    		}
    		else {
    			$new_width = $width;
    			$new_height = $height;
    		}
    				
    		$newImage = imagecreatetruecolor($new_width, $new_height);
    		@imagecopyresampled($newImage,$this->im,0,0,0,0,$new_width,$new_height,$width,$height);
    		
    		$this->im = $newImage;
    		
    		return $this;
    		
    	}
    	
    	public static function load($file) {
    		return new self($file);
    	}
    	
    	public function saveToFile($dest, $type = 'default') {
    		if($type == 'default') {
    			$ext = $this->ext;
    			call_user_func('image' . current($ext), &$this->im, $dest);	
    			
    		}
    		
    		else {
    		
    			call_user_func('image' . $type, &$this->im, $dest);
    		
    		}
    		
    	}
    	
    	public function __clone() {
    	
    		// reload from file so we don't have the same resources
    		$this->loadFile($this->src);
    	
    	}
    
    }
    
    
    ?>
    Here's an example of how you'd use it:
    Code:
    $pathToImage = '/myimages/bigpic.jpg';
    $pathToDestination = '/myimages/thumbnails/bigpic.jpg';
    
    My_Image::load($pathToImage)->resize(300, 300)->saveToFile($pathToDestination);
    
    // or
    
    $image = new My_Image($pathToImage);
    $secondImage = clone $image;
    $image->saveToFile('/whatever/whatever.jpg', 'jpeg');
    $secondImage->resize(300,300)->saveToFile('/whatever/thumbs/whatever.gif', 'gif');
    Last edited by jackbenimble4; 02-16-2008 at 03:06 PM.

  7. #7
    Join Date
    Feb 2008
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Help Me!

    how to resize height for Image & thumbnail on this sample

    PHP Code:
    function addProduct()
    {
    $catId $_POST['cboCategory'];
    $name $_POST['txtName'];
    $description $_POST['mtxDescription'];
    $price str_replace(',''', (double)$_POST['txtPrice']);
    $qty = (int)$_POST['txtQty'];
    $sale $_POST['cboSale'];
    $notes $_POST['mtxNotes'];

    $images uploadProductImage('fleImage'SRV_ROOT 'images/');

    $mainImage $images['image'];
    $thumbnail $images['thumbnail'];

    $sql "INSERT INTO tbl_product (cat_id, pd_name, pd_description, pd_price, pd_qty, pd_image, pd_thumbnail, pd_date, pd_sale, pd_notes)
    VALUES ('
    $catId', '$name', '$description', $price$qty, '$mainImage', '$thumbnail', NOW(), '$sale', '$notes')";
    $result dbQuery($sql);

    header("Location: index.php?catId=$catId");
    }

    //Upload an image and return the uploaded image name
    function uploadProductImage($inputName$uploadDir)
    {
    $image $_FILES[$inputName];
    $imagePath '';
    $thumbnailPath '';

    // if a file is given
    if (trim($image['tmp_name']) != '') {
    $ext substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

    // generate a random new file name to avoid name conflict
    $imagePath md5(rand() * time()) . ".$ext";

    list(
    $width$height$type$attr) = getimagesize($image['tmp_name']);

    // make sure the image width does not exceed the maximum allowed width
    if (LIMIT_PRODUCT_WIDTH && $width MAX_PRODUCT_IMAGE_WIDTH) {
    $result createThumbnail($image['tmp_name'], $uploadDir $imagePathMAX_PRODUCT_IMAGE_WIDTH);
    $imagePath $result;
    } else {
    $result move_uploaded_file($image['tmp_name'], $uploadDir $imagePath);
    }

    if (
    $result) {
    // create thumbnail
    $thumbnailPath md5(rand() * time()) . ".$ext";
    $result createThumbnail($uploadDir $imagePath$uploadDir $thumbnailPathTHUMBNAIL_WIDTH);

    // create thumbnail failed, delete the image
    if (!$result) {
    unlink($uploadDir $imagePath);
    $imagePath $thumbnailPath '';
    } else {
    $thumbnailPath $result;
    }
    } else {
    // the product cannot be upload / resized
    $imagePath $thumbnailPath '';
    }
    }
    return array(
    'image' => $imagePath'thumbnail' => $thumbnailPath);
    }

    //Create a thumbnail of $srcFile and save it to $destFile; The thumbnail will be $width pixels
    function createThumbnail($srcFile$destFile$width$quality 75)
    {
    $thumbnail '';

    if (
    file_exists($srcFile) && isset($destFile))
    {
    $size getimagesize($srcFile);
    $w number_format($width0',''');
    $h number_format(($size[1] / $size[0]) * $width0',''');

    $thumbnail copyImage($srcFile$destFile$w$h$quality);
    }

    // return the thumbnail file name on sucess or blank on fail
    return basename($thumbnail);
    }

    //copy an image to a destination file. The destination image size will be $w X $h pixels
    function copyImage($srcFile$destFile$w$h$quality 75)
    {
    $tmpSrc pathinfo(strtolower($srcFile));
    $tmpDest pathinfo(strtolower($destFile));
    $size getimagesize($srcFile);

    if (
    $tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
    $destFile substr_replace($destFile'jpg', -3);
    $dest imagecreatetruecolor($w$h);
    imageantialias($destTRUE);
    } elseif (
    $tmpDest['extension'] == "png") {
    $dest imagecreatetruecolor($w$h);
    imageantialias($destTRUE);
    } else {
    return 
    false;
    }

    switch(
    $size[2])
    {
    case 
    1//GIF
    $src imagecreatefromgif($srcFile);
    break;
    case 
    2//JPEG
    $src imagecreatefromjpeg($srcFile);
    break;
    case 
    3//PNG
    $src imagecreatefrompng($srcFile);
    break;
    default:
    return 
    false;
    break;
    }

    imagecopyresampled($dest$src0000$w$h$size[0], $size[1]);

    switch(
    $size[2])
    {
    case 
    1:
    case 
    2:
    imagejpeg($dest,$destFile$quality);
    break;
    case 
    3:
    imagepng($dest,$destFile);
    }
    return 
    $destFile;



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
  •