Page 1 of 2

Thumbnails...need help please.

Posted: Mon Apr 09, 2012 5:45 pm
by meduser
Hi..I am very new to php, but get the basic concepts....or so I thought..


I am trying to make a website...for the most part I am successful. I am having a couple of issues.

I am trying to make the images into thumbnails. I have found many different types of thumbnails online, but I don't understand how it works...
I do have the GD library.
I want to use a code similar to this:

Code: Select all

<?php

require_once('thumbnail.inc.php');

/**
 * Create thumbnail images for the images directory!
 */
public function createThumbs() {
                
        $pathName = dirname(__FILE__) . '/images/';
                
        // create an array containing the list of thumbnails 
        // this will be passed from the controller to the view
        $thumbFiles = array();


        // DirectoryIterator is part of the Standard PHP library        
        foreach(new DirectoryIterator($pathName) as $fileInfo) {
                        
                $fileName = $fileInfo->getFileName();
                
                if ($fileInfo->isDir()) {
                        continue;
                }
                        
                // TODO: we should also check if this file 
                // already has a thumbnail generated!!
                
                // skip thumbnails that have already been generated
                //                      
                $pos = strpos($fileName, "_Thumb.");
                if ($pos !== false) {
                        //$thumbFiles[] = $thumbFileName;       
                        continue;       
                }
                        
                $thumb = new Thumbnail($pathName . $fileName);
                $thumb->resize(200, 100);
                
                // create a new fileName with 'Small' in it 
                // (e.g. pic.jpg -> picSmall.jpg)
                //
                $thumbFileName = 
                substr_replace($fileName, "_Thumb", strpos($fileName, '.'));
                        
                // add the file extension back
                $thumbFileName .= '.' . substr($fileName, -3);
                 
                $thumb->save($pathName . $thumbFileName);
                        
                // add this to our array containing the list of thumbnail files
                $thumbFiles[] = $thumbFileName; 
                        
                //echo $fileInfo . "\n";
        }
        return $thumbFiles;
}

?>
 

along with this file:

Code: Select all

<?php
/**
 * thumbnail.inc.php
 * 
 */


class Thumbnail {
    /**
     * Error message to display, if any
     *
     * @var string
     */
    private $errmsg;
    /**
     * Whether or not there is an error
     *
     * @var boolean
     */
    private $error;
    /**
     * Format of the image file
     *
     * @var string
     */
    private $format;
    /**
     * File name and path of the image file
     *
     * @var string
     */
    private $fileName;
    /**
     * Image meta data if any is available (jpeg/tiff) via the exif library
     *
     * @var array
     */
    public $imageMeta;
    /**
     * Current dimensions of working image
     *
     * @var array
     */
    private $currentDimensions;
    /**
     * New dimensions of working image
     *
     * @var array
     */
    private $newDimensions;
    /**
     * Image resource for newly manipulated image
     *
     * @var resource
     */
    private $newImage;
    /**
     * Image resource for image before previous manipulation
     *
     * @var resource
     */
    private $oldImage;
    /**
     * Image resource for image being currently manipulated
     *
     * @var resource
     */
    private $workingImage;
    /**
     * Percentage to resize image by
     *
     * @var int
     */
    private $percent;
    /**
     * Maximum width of image during resize
     *
     * @var int
     */
    private $maxWidth;
    /**
     * Maximum height of image during resize
     *
     * @var int
     */
    private $maxHeight;

    /**
     * Class constructor
     *
     * @param string $fileName
     * @return Thumbnail
     */
    public function __construct($fileName) {
        //make sure the GD library is installed
        if(!function_exists("gd_info")) {
                echo 'You do not have the GD Library installed.  This class requires the GD library to function properly.' . "\n";
                echo 'visit http://us2.php.net/manual/en/ref.image.php for more information';
                exit;
        }
        //initialize variables
        $this->errmsg               = '';
        $this->error                = false;
        $this->currentDimensions    = array();
        $this->newDimensions        = array();
        $this->fileName             = $fileName;
        $this->imageMeta                        = array();
        $this->percent              = 100;
        $this->maxWidth             = 0;
        $this->maxHeight            = 0;

        //check to see if file exists
        if(!file_exists($this->fileName)) {
            $this->errmsg = 'File not found';
            $this->error = true;
        }
        //check to see if file is readable
        elseif(!is_readable($this->fileName)) {
            $this->errmsg = 'File is not readable';
            $this->error = true;
        }

        //if there are no errors, determine the file format
        if($this->error == false) {
            //check if gif
            if(stristr(strtolower($this->fileName),'.gif')) $this->format = 'GIF';
            //check if jpg
            elseif(stristr(strtolower($this->fileName),'.jpg') || stristr(strtolower($this->fileName),'.jpeg')) $this->format = 'JPG';
            //check if png
            elseif(stristr(strtolower($this->fileName),'.png')) $this->format = 'PNG';
            //unknown file format
            else {
                $this->errmsg = 'Unknown file format';
                $this->error = true;
            }
        }

        //initialize resources if no errors
        if($this->error == false) {
            switch($this->format) {
                case 'GIF':
                    $this->oldImage = ImageCreateFromGif($this->fileName);
                    break;
                case 'JPG':
                    $this->oldImage = ImageCreateFromJpeg($this->fileName);
                    break;
                case 'PNG':
                    $this->oldImage = ImageCreateFromPng($this->fileName);
                    break;
            }

            $size = GetImageSize($this->fileName);
            $this->currentDimensions = array('width'=>$size[0],'height'=>$size[1]);
            $this->newImage = $this->oldImage;
            $this->gatherImageMeta();
        }

        if($this->error == true) {
            $this->showErrorImage();
            break;
        }
    }

    /**
     * Class destructor
     *
     */
    public function __destruct() {
        if(is_resource($this->newImage)) @ImageDestroy($this->newImage);
        if(is_resource($this->oldImage)) @ImageDestroy($this->oldImage);
        if(is_resource($this->workingImage)) @ImageDestroy($this->workingImage);
    }

    /**
     * Returns the current width of the image
     *
     * @return int
     */
    private function getCurrentWidth() {
        return $this->currentDimensions['width'];
    }

    /**
     * Returns the current height of the image
     *
     * @return int
     */
    private function getCurrentHeight() {
        return $this->currentDimensions['height'];
    }

    /**
     * Calculates new image width
     *
     * @param int $width
     * @param int $height
     * @return array
     */
    private function calcWidth($width,$height) {
        $newWp = (100 * $this->maxWidth) / $width;
        $newHeight = ($height * $newWp) / 100;
        return array('newWidth'=>intval($this->maxWidth),'newHeight'=>intval($newHeight));
    }

    /**
     * Calculates new image height
     *
     * @param int $width
     * @param int $height
     * @return array
     */
    private function calcHeight($width,$height) {
        $newHp = (100 * $this->maxHeight) / $height;
        $newWidth = ($width * $newHp) / 100;
        return array('newWidth'=>intval($newWidth),'newHeight'=>intval($this->maxHeight));
    }

    /**
     * Calculates new image size based on percentage
     *
     * @param int $width
     * @param int $height
     * @return array
     */
    private function calcPercent($width,$height) {
        $newWidth = ($width * $this->percent) / 100;
        $newHeight = ($height * $this->percent) / 100;
        return array('newWidth'=>intval($newWidth),'newHeight'=>intval($newHeight));
    }

    /**
     * Calculates new image size based on width and height, while constraining to maxWidth and maxHeight
     *
     * @param int $width
     * @param int $height
     */
    private function calcImageSize($width,$height) {
        $newSize = array('newWidth'=>$width,'newHeight'=>$height);

        if($this->maxWidth > 0) {

            $newSize = $this->calcWidth($width,$height);

            if($this->maxHeight > 0 && $newSize['newHeight'] > $this->maxHeight) {
                $newSize = $this->calcHeight($newSize['newWidth'],$newSize['newHeight']);
            }

            //$this->newDimensions = $newSize;
        }

        if($this->maxHeight > 0) {
            $newSize = $this->calcHeight($width,$height);

            if($this->maxWidth > 0 && $newSize['newWidth'] > $this->maxWidth) {
                $newSize = $this->calcWidth($newSize['newWidth'],$newSize['newHeight']);
            }

            //$this->newDimensions = $newSize;
        }

        $this->newDimensions = $newSize;
    }

    /**
     * Calculates new image size based percentage
     *
     * @param int $width
     * @param int $height
     */
    private function calcImageSizePercent($width,$height) {
        if($this->percent > 0) {
            $this->newDimensions = $this->calcPercent($width,$height);
        }
    }

    /**
     * Displays error image
     *
     */
    private function showErrorImage() {
        header('Content-type: image/png');
        $errImg = ImageCreate(220,25);
        $bgColor = imagecolorallocate($errImg,0,0,0);
        $fgColor1 = imagecolorallocate($errImg,255,255,255);
        $fgColor2 = imagecolorallocate($errImg,255,0,0);
        imagestring($errImg,3,6,6,'Error:',$fgColor2);
        imagestring($errImg,3,55,6,$this->errmsg,$fgColor1);
        imagepng($errImg);
        imagedestroy($errImg);
    }

    /**
     * Resizes image to maxWidth x maxHeight
     *
     * @param int $maxWidth
     * @param int $maxHeight
     */
    public function resize($maxWidth = 0, $maxHeight = 0) {
        $this->maxWidth = $maxWidth;
        $this->maxHeight = $maxHeight;

        $this->calcImageSize($this->currentDimensions['width'],$this->currentDimensions['height']);

                if(function_exists("ImageCreateTrueColor")) {
                        $this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
                }
                else {
                        $this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
                }

                ImageCopyResampled(
                        $this->workingImage,
                        $this->oldImage,
                        0,
                        0,
                        0,
                        0,
                        $this->newDimensions['newWidth'],
                        $this->newDimensions['newHeight'],
                        $this->currentDimensions['width'],
                        $this->currentDimensions['height']
                );

                $this->oldImage = $this->workingImage;
                $this->newImage = $this->workingImage;
                $this->currentDimensions['width'] = $this->newDimensions['newWidth'];
                $this->currentDimensions['height'] = $this->newDimensions['newHeight'];
        }

        /**
         * Resizes the image by $percent percent
         *
         * @param int $percent
         */
        public function resizePercent($percent = 0) {
            $this->percent = $percent;

            $this->calcImageSizePercent($this->currentDimensions['width'],$this->currentDimensions['height']);

                if(function_exists("ImageCreateTrueColor")) {
                        $this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
                }
                else {
                        $this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
                }

                ImageCopyResampled(
                        $this->workingImage,
                        $this->oldImage,
                        0,
                        0,
                        0,
                        0,
                        $this->newDimensions['newWidth'],
                        $this->newDimensions['newHeight'],
                        $this->currentDimensions['width'],
                        $this->currentDimensions['height']
                );

                $this->oldImage = $this->workingImage;
                $this->newImage = $this->workingImage;
                $this->currentDimensions['width'] = $this->newDimensions['newWidth'];
                $this->currentDimensions['height'] = $this->newDimensions['newHeight'];
        }

        /**
         * Crops the image from calculated center in a square of $cropSize pixels
         *
         * @param int $cropSize
         */
        public function cropFromCenter($cropSize) {
            if($cropSize > $this->currentDimensions['width']) $cropSize = $this->currentDimensions['width'];
            if($cropSize > $this->currentDimensions['height']) $cropSize = $this->currentDimensions['height'];

            $cropX = intval(($this->currentDimensions['width'] - $cropSize) / 2);
            $cropY = intval(($this->currentDimensions['height'] - $cropSize) / 2);

            if(function_exists("ImageCreateTrueColor")) {
                        $this->workingImage = ImageCreateTrueColor($cropSize,$cropSize);
                }
                else {
                        $this->workingImage = ImageCreate($cropSize,$cropSize);
                }

                imagecopyresampled(
            $this->workingImage,
            $this->oldImage,
            0,
            0,
            $cropX,
            $cropY,
            $cropSize,
            $cropSize,
            $cropSize,
            $cropSize
                );

                $this->oldImage = $this->workingImage;
                $this->newImage = $this->workingImage;
                $this->currentDimensions['width'] = $cropSize;
                $this->currentDimensions['height'] = $cropSize;
        }

        /**
         * Advanced cropping function that crops an image using $startX and $startY as the upper-left hand corner.
         *
         * @param int $startX
         * @param int $startY
         * @param int $width
         * @param int $height
         */
        public function crop($startX,$startY,$width,$height) {
            //make sure the cropped area is not greater than the size of the image
            if($width > $this->currentDimensions['width']) $width = $this->currentDimensions['width'];
            if($height > $this->currentDimensions['height']) $height = $this->currentDimensions['height'];
            //make sure not starting outside the image
            if(($startX + $width) > $this->currentDimensions['width']) $startX = ($this->currentDimensions['width'] - $width);
            if(($startY + $height) > $this->currentDimensions['height']) $startY = ($this->currentDimensions['height'] - $height);
            if($startX < 0) $startX = 0;
            if($startY < 0) $startY = 0;

            if(function_exists("ImageCreateTrueColor")) {
                        $this->workingImage = ImageCreateTrueColor($width,$height);
                }
                else {
                        $this->workingImage = ImageCreate($width,$height);
                }

                imagecopyresampled(
            $this->workingImage,
            $this->oldImage,
            0,
            0,
            $startX,
            $startY,
            $width,
            $height,
            $width,
            $height
                );

                $this->oldImage = $this->workingImage;
                $this->newImage = $this->workingImage;
                $this->currentDimensions['width'] = $width;
                $this->currentDimensions['height'] = $height;
        }

        /**
         * Outputs the image to the screen, or saves to $name if supplied.  Quality of JPEG images can be controlled with the $quality variable
         *
         * @param int $quality
         * @param string $name
         */
        public function show($quality=100,$name = '') {
            switch($this->format) {
                case 'GIF':
                    if($name != '') {
                        ImageGif($this->newImage,$name);
                    }
                    else {
                       header('Content-type: image/gif');
                       ImageGif($this->newImage);
                    }
                    break;
                case 'JPG':
                    if($name != '') {
                        ImageJpeg($this->newImage,$name,$quality);
                    }
                    else {
                       header('Content-type: image/jpeg');
                       ImageJpeg($this->newImage,'',$quality);
                    }
                    break;
                case 'PNG':
                    if($name != '') {
                        ImagePng($this->newImage,$name);
                    }
                    else {
                       header('Content-type: image/png');
                       ImagePng($this->newImage);
                    }
                    break;
            }
        }

        /**
         * Saves image as $name (can include file path), with quality of # percent if file is a jpeg
         *
         * @param string $name
         * @param int $quality
         */
        public function save($name,$quality=100) {
            $this->show($quality,$name);
        }

        /**
         * Creates Apple-style reflection under image, optionally adding a border to main image
         *
         * @param int $percent
         * @param int $reflection
         * @param int $white
         * @param bool $border
         * @param string $borderColor
         */
        public function createReflection($percent,$reflection,$white,$border = true,$borderColor = '#a4a4a4') {
        $width = $this->currentDimensions['width'];
        $height = $this->currentDimensions['height'];

        $reflectionHeight = intval($height * ($reflection / 100));
        $newHeight = $height + $reflectionHeight;
        $reflectedPart = $height * ($percent / 100);

        $this->workingImage = ImageCreateTrueColor($width,$newHeight);

        ImageAlphaBlending($this->workingImage,true);

        $colorToPaint = ImageColorAllocateAlpha($this->workingImage,255,255,255,0);
        ImageFilledRectangle($this->workingImage,0,0,$width,$newHeight,$colorToPaint);

        imagecopyresampled(
                            $this->workingImage,
                            $this->newImage,
                            0,
                            0,
                            0,
                            $reflectedPart,
                            $width,
                            $reflectionHeight,
                            $width,
                            ($height - $reflectedPart));
        $this->imageFlipVertical();

        imagecopy($this->workingImage,$this->newImage,0,0,0,0,$width,$height);

        imagealphablending($this->workingImage,true);

        for($i=0;$i<$reflectionHeight;$i++) {
            $colorToPaint = imagecolorallocatealpha($this->workingImage,255,255,255,($i/$reflectionHeight*-1+1)*$white);
            imagefilledrectangle($this->workingImage,0,$height+$i,$width,$height+$i,$colorToPaint);
        }

        if($border == true) {
            $rgb = $this->hex2rgb($borderColor,false);
            $colorToPaint = imagecolorallocate($this->workingImage,$rgb[0],$rgb[1],$rgb[2]);
            imageline($this->workingImage,0,0,$width,0,$colorToPaint); //top line
            imageline($this->workingImage,0,$height,$width,$height,$colorToPaint); //bottom line
            imageline($this->workingImage,0,0,0,$height,$colorToPaint); //left line
            imageline($this->workingImage,$width-1,0,$width-1,$height,$colorToPaint); //right line
        }

        $this->oldImage = $this->workingImage;
                $this->newImage = $this->workingImage;
                $this->currentDimensions['width'] = $width;
                $this->currentDimensions['height'] = $newHeight;
        }

        /**
         * Inverts working image, used by reflection function
         * 
         */
        private function imageFlipVertical() {
            $x_i = imagesx($this->workingImage);
            $y_i = imagesy($this->workingImage);

            for($x = 0; $x < $x_i; $x++) {
                for($y = 0; $y < $y_i; $y++) {
                    imagecopy($this->workingImage,$this->workingImage,$x,$y_i - $y - 1, $x, $y, 1, 1);
                }
            }
        }

        /**
         * Converts hexidecimal color value to rgb values and returns as array/string
         *
         * @param string $hex
         * @param bool $asString
         * @return array|string
         */
        private function hex2rgb($hex, $asString = false) {
        // strip off any leading #
        if (0 === strpos($hex, '#')) {
           $hex = substr($hex, 1);
        } else if (0 === strpos($hex, '&H')) {
           $hex = substr($hex, 2);
        }

        // break into hex 3-tuple
        $cutpoint = ceil(strlen($hex) / 2)-1;
        $rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

        // convert each tuple to decimal
        $rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
        $rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
        $rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

        return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
    }
    
    /**
     * Reads selected exif meta data from jpg images and populates $this->imageMeta with appropriate values if found
     *
     */
    private function gatherImageMeta() {
        //only attempt to retrieve info if exif exists
        if(function_exists("exif_read_data") && $this->format == 'JPG') {
                        $imageData = exif_read_data($this->fileName);
                        if(isset($imageData['Make'])) 
                                $this->imageMeta['make'] = ucwords(strtolower($imageData['Make']));
                        if(isset($imageData['Model'])) 
                                $this->imageMeta['model'] = $imageData['Model'];
                        if(isset($imageData['COMPUTED']['ApertureFNumber'])) {
                                $this->imageMeta['aperture'] = $imageData['COMPUTED']['ApertureFNumber'];
                                $this->imageMeta['aperture'] = str_replace('/','',$this->imageMeta['aperture']);
                        }
                        if(isset($imageData['ExposureTime'])) {
                                $exposure = explode('/',$imageData['ExposureTime']);
                                $exposure = round($exposure[1]/$exposure[0],-1);
                                $this->imageMeta['exposure'] = '1/' . $exposure . ' second';
                        }
                        if(isset($imageData['Flash'])) {
                                if($imageData['Flash'] > 0) {
                                        $this->imageMeta['flash'] = 'Yes';
                                }
                                else {
                                        $this->imageMeta['flash'] = 'No';
                                }
                        }
                        if(isset($imageData['FocalLength'])) {
                                $focus = explode('/',$imageData['FocalLength']);
                                $this->imageMeta['focalLength'] = round($focus[0]/$focus[1],2) . ' mm';
                        }
                        if(isset($imageData['DateTime'])) {
                                $date = $imageData['DateTime'];
                                $date = explode(' ',$date);
                                $date = str_replace(':','-',$date[0]) . ' ' . $date[1];
                                $this->imageMeta['dateTaken'] = date('m/d/Y g:i A',strtotime($date));
                        }
        }
    }
    
    /**
     * Rotates image either 90 degrees clockwise or counter-clockwise
     *
     * @param string $direction
     */
    public function rotateImage($direction = 'CW') {
        if($direction == 'CW') {
                $this->workingImage = imagerotate($this->workingImage,-90,0);
        }
        else {
                $this->workingImage = imagerotate($this->workingImage,90,0);
        }
        $newWidth = $this->currentDimensions['height'];
        $newHeight = $this->currentDimensions['width'];
                $this->oldImage = $this->workingImage;
                $this->newImage = $this->workingImage;
                $this->currentDimensions['width'] = $newWidth;
                $this->currentDimensions['height'] = $newHeight;
    }
}
?>
Now, I know the code works for thumbnails as some classmates have had some luck in getting it going, but I have not.

My images are set in tables made in MYSql, and this is for a basic shopping cart.

I am trying to get it so that the listings on my products page shows a small image, but blows up onclick or mouse-over.

I just don't understand how to implement these two php pages to make thumbnails.

My products page looks like this:

Code: Select all

<?php
	include("includes/db.php");
	include("includes/functions.php");
	if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){
		remove_product($_REQUEST['pid']);
	}
	else if($_REQUEST['command']=='clear'){
		unset($_SESSION['cart']);
	}
	else if($_REQUEST['command']=='update'){
		$max=count($_SESSION['cart']);
		for($i=0;$i<$max;$i++){
			$pid=$_SESSION['cart'][$i]['productid'];
			$q=intval($_REQUEST['product'.$pid]);
			if($q>0 && $q<=999){
				$_SESSION['cart'][$i]['qty']=$q;
			}
			else{
				$msg='Some products not updated!, quantity must be a number between 1 and 999';
			}
		}
	}
	if ( isset($_REQUEST['command']) && isset($_REQUEST['productid']) ) {
		if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){
			$pid=$_REQUEST['productid'];
			addtocart($pid,1);
			header("location:shoppingcart.php");
			exit();
		}
	}
?>

<!DOCTYPE html >

<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<title>Gary's Blog</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>

function ajaxSearch() {
	
	var searchstring = $('#searchstring').val();
	console.log("Searching for " + searchstring);
	
	var data = new Object();
    
    // basically you just add 'attributes' to the data object
    data.search = searchstring;
 
    // : this uses the built-in JSON object for modern browsers
    var dataString = JSON.stringify(data);
 
	$.post("ajaxSearch.php", { data: dataString },
		function(response) { 
 
		// Note JSON.parse is only available in modern browsers
		var obj = JSON.parse(response);
 
		// find the div with id='result' and set the html to this string
		// returned by the phpfile
		//
		//$("#result").html(obj.value + "! This message was sent from JavaScript to PHP and back again<br /><br />" +
		// "This message is from PHP: "+obj.php_message);
 
		console.log("Debug message from server is: " + obj.debugMessage);
 
		//console.log("New position is: " + obj.answer); 
		
		console.log("Done");
 
	}); 	
}


</script>

</head>
	<body>
         <a id="pagetop"></a>
		<div id="wrapper">


<?php include('includes/header.php'); ?>

<?php include('includes/nav.php'); ?>
<div id="content">

<script language="javascript">
	function addtocart(pid){
		document.form1.productid.value=pid;
		document.form1.command.value='add';
		document.form1.submit();
	}
</script>
</head>


<body>
	<h1 align="center">Flyers Game Worn Merchandise:</h1>
	<div align="center">
		<td colspan="5" align="right"><input type="button" value= "View Cart" onclick="window.location='shoppingcart.php'"/>
	<td colspan="5" align="right"><input type="button" value= "Collectables" onclick="window.location='collectables.php'"/>
<td colspan="5" align="right"><input type="button" value= "Autographed" onclick="window.location='autographs.php'"/>
</div>
		<form action="index.php" method="get">

<form>
<tr>
	
<td><b>Search for a players sweater:</b></td>
<td><input type="text" id="searchstring" name="searchstring" size="10" value=""></td>
<td><input type="button" value="Search" border="0" onclick="ajaxSearch()"></td>
</tr>
</form>

</form>
<form name="form1">
	<input type="hidden" name="productid" />
    <input type="hidden" name="command" />
</form>

<div align="center">
	
	<table border="0" cellpadding="2px" width="600px">
		<?
			$result=mysql_query("select * from products where serial < 1500");
			while($row=mysql_fetch_array($result)){
		?>
    	<tr>
        	<td><img src="<?=$row['picture']?>" /></td>
            <td>   	<b><?=$row['name']?></b><br />
            		<?=$row['description']?><br />
                    Price:<big style="color:red">
                    	$<?=$row['price']?></big><br /><br />
                    <input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" />
			</td>
		</tr>
        <tr><td colspan="2"><hr size="1" /></td>
        <? } ?>
    </table>
</div>


<td colspan="5" align="right"><a href="#pagetop"><input type="button" value= "Return to top" onclick="Back to top" class="imageright"></a>
<td colspan="5" align="right"><input type="button" value= "Return to Homepage" onclick="window.location='../index.php'" />
<td colspan="5" align="right"><input type="button" value= "Logout" onclick="window.location='../logout.php'"></a>
</div> <!-- end #content -->


<?php include('includes/sidebar.php'); ?>

<?php include('includes/footer.php'); ?>

		</div> <!-- End #wrapper -->

	</body>

</html>


so I don't know how to make this work..can someone please find it to help me get this done?

Thank you in advance.

Re: Thumbnails...need help please.

Posted: Mon Apr 09, 2012 10:17 pm
by Christopher
You need to simplify your question and just show the code where you think the problem is.

Re: Thumbnails...need help please.

Posted: Mon Apr 09, 2012 10:56 pm
by meduser
all the code works..Some classmates have used the thumbnails pages to make thumbnails for their sites.

I don't know what to do with the code. How do I get it to make the thumbnails?

Do I add it to the top of the sweaters script?

I don't know what to do with the script. I missed class the day the instructor went over how to use the files.

I have a full site on a development server. I am just trying to make the images into thumbnails for quicker page downloads. What do I do with the two php files for thumbnails? Do I put them with the images? I am just completely lost. I know the sweaters product page works fine on the server, I just don't know how to make them work together with an image folder that has contains large images.

Basically at the risk of sounding completely dumb...how can I use the above two php files for making thumbnails for a website?

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 7:49 am
by meduser
I am still at a loss. It has been almost 24 hours, and only one response, telling me I gave to much info.


I am asking for help because I don't know, someone has to know how to implement thumbnails.

I love it when people don't help..I already posted the same post in tutorials, looking for a how to. All I got was it works, but I don't like it. I am asking how to make it work. I see other people being helped, I just don't think this is that big of a question. Very general, and I am just frustrated.

My assignment is due today, and I can't get thumbnails working right.

Can someone help me please?

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 10:05 am
by meduser
ANybody??????????

guess not.

Why have a forum if nobody even reads the posts? I have wasted 2 days coming here, only to be told off by a mod, and have someone say..yes, it works.

My questions are about how to use it, not about if it works or not.

I have sent pm's to one of the two who responded, and still no response...is it really that hard to direct a newbie on how to use a file? Is that really so hard.

I have found nothing online on this, next to different versions of the same files.

Just how the hell do you use these files to get the thumbnails to be generated?

Anyone..post a link if you don't want to explain, but cmon...someone has to have used thumbnails here....

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 10:11 am
by Celauran
First, you need to remove the 'public' before function createThumbs() as it does not belong to a class. As the function accepts no arguments and works on an existing directory, it would seem easiest to simply add a function call to the bottom of the script and call the script directly when you need to process the directory. It will create a thumbnail of every image in the /images/ subdirectory and append _Thumb to the filename.

So, assuming you've got the path to each item's image stored in your database, you can simply append _Thumb to display the thumbnail instead and wrap it in a link to the full-size image.

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 10:35 am
by meduser
but it does belong to a class...
PHP class for dynamically resizing, cropping, and rotating images for thumbnail purposes and either displaying them on-the-fly or saving them.
class Thumbnail {
/**
* Error message to display, if any
*
* @var string
*/

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 10:40 am
by Celauran
No, the other file. It specifically requires thumbnail.inc.php. If you removed that function from the class, why?

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 11:10 am
by meduser
it is my understanding that the files work without needing to be altered. I did not delete or remove anything, accept for the comments at the top of the file.
the download from the instructor was two files...createThumbs.php and thumbnail.inc.php

The function calls are all in the thumbnail.inc.php file....

again..sorry for being so dumb with this, but I thought it was simple, and I am just completely stumped. I know it should be easy....so, I have the two files..

I have gone into my database and changed the image locations from:
images/daniel-briere-autographed-photo-8x10-jsa-1-t1620879-500.jpg
to:
images/daniel-briere-autographed-photo-8x10-jsa-1-t1620879-500_Thumb.jpg

You say "easiest to simply add a function call to the bottom of the script and call the script directly when you need to process the directory. It will create a thumbnail of every image in the /images/ subdirectory and append _Thumb to the filename."

would this function call go onto the products page?

For example the above image is on the autographs page. The database is called shopping. The table in the database is called products. The images are placed onto the products page from the products table. So would I place the function at the top of the autographs page?

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 11:27 am
by Celauran
meduser wrote:The function calls are all in the thumbnail.inc.php file....
No, those are the function definitions.
meduser wrote:I have gone into my database and changed the image locations from:
images/daniel-briere-autographed-photo-8x10-jsa-1-t1620879-500.jpg
to:
images/daniel-briere-autographed-photo-8x10-jsa-1-t1620879-500_Thumb.jpg
Comes down to the same thing. Now you'll have to remove '_Thumb' to link to the full-sized image.
meduser wrote:You say "easiest to simply add a function call to the bottom of the script and call the script directly when you need to process the directory. It will create a thumbnail of every image in the /images/ subdirectory and append _Thumb to the filename."

would this function call go onto the products page?

For example the above image is on the autographs page. The database is called shopping. The table in the database is called products. The images are placed onto the products page from the products table. So would I place the function at the top of the autographs page?
Depends on your use case, I suppose. That's not how I'd do it, though. createThumbs() just blindly goes through the directory creating thumbnails of everything, including images that already have thumbnails created. It's a lot of needless duplication. A better solution would be to just run it once to create thumbnails for whatever is initially in that directory and be done with it. As you add new images, create their thumbnails at the same time using the Thumbnail class defined in thumbnail.inc.php

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 11:40 am
by meduser
" A better solution would be to just run it once to create thumbnails for whatever is initially in that directory and be done with it"

That sounds great. I was under the impression the thumbnails would be made, then I just add the thumbs to the databases.

I know this shows how new I am to this...how do I just run it? Once the thumbs are made, I can continue with the site.

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 11:42 am
by Celauran
Simply add a line to the bottom of the file

Code: Select all

createThumbs();
Then point your browser to that file. It should create thumbs for every image currently in the directory. Before running it, make sure Apache has write permission to the /images/ directory.

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 11:53 am
by meduser
createThumbs() just blindly goes through the directory creating thumbnails of everything, including images that already have thumbnails created.
doesn't this prevent this?

Code: Select all

// TODO: we should also check if this file 
                // already has a thumbnail generated!!
                
                // skip thumbnails that have already been generated
                //                      
                $pos = strpos($fileName, "_Thumb.");
                if ($pos !== false) {
                        //$thumbFiles[] = $thumbFileName;       
                        continue;       
                }
                        
                $thumb = new Thumbnail($pathName . $fileName);
                $thumb->resize(200, 100);
You say to:
Simply add a line to the bottom of the file

createThumbs();
what file? the login page? the createThumbs php?

Can you explain how this works.

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 12:02 pm
by Celauran
meduser wrote:
createThumbs() just blindly goes through the directory creating thumbnails of everything, including images that already have thumbnails created.
doesn't this prevent this?

Code: Select all

// TODO: we should also check if this file 
                // already has a thumbnail generated!!
                
                // skip thumbnails that have already been generated
                //                      
                $pos = strpos($fileName, "_Thumb.");
                if ($pos !== false) {
                        //$thumbFiles[] = $thumbFileName;       
                        continue;       
                }
                        
                $thumb = new Thumbnail($pathName . $fileName);
                $thumb->resize(200, 100);
It's a TODO comment, indicating quite clearly that it's functionality not yet incorporated, so no.
meduser wrote:You say to:
Simply add a line to the bottom of the file

createThumbs();
what file? the login page? the createThumbs php?

Can you explain how this works.
createThumbs.php

The file, as you posted it above, contains only the function definition. Ostensibly, you'd call the function from other pages but, as I explained previously, that doesn't really make a lot of sense. We add the function call right after the function definition, call the file once to create the initial batch of thumbs, and use a better solution going forward.

Re: Thumbnails...need help please.

Posted: Tue Apr 10, 2012 12:04 pm
by meduser
ok, tryint this again..just saw your response.

I appreciate your help...and your patience with my lack of knowledge.