Page 2 of 4 FirstFirst 1234 LastLast
Results 11 to 20 of 32

Thread: images/directory listing script

  1. #11
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    UPDATE:
    (The code for thumbnails.php is the same, and still required. See above.)

    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <title>Image Browser</title>
        <style type="text/css">
          ul.dirlist, ul.dirlist li {
            list-style-type: none;
          }
          a {
              color: #0000FF;
          }
          div.border {
          border-left-style: solid;
          border-bottom-style: solid;
          border-color: #000066;
          border-width: thin;
          }
        </style>
      </head>
      <body bgcolor="#000000" text="#0000FF">
        <?php
          $page 
    substr($_SERVER['SCRIPT_NAME'],(strrpos($_SERVER['SCRIPT_NAME'],"/")+1));
          function 
    checkDir($c,$skipimages=0) {
            echo(
    '<div class="border"><ul class="dirlist">');
            
    $d opendir($c);
            while(
    $f readdir($d)) {
              if(
    strpos($f'.') === 0) continue;
              
    $ff $c '/' $f;
              if (
    strpos(strtolower($f), '.jpg') !== FALSE && $skipimages != 3) {
                  if (
    $skipimages != 1) {          
                  
    $fff '<img src="thumbnail.php?image='.urlencode($ff).'" border="">';
                  echo(
    '<a href="' $ff '">' $fff '</a>'."\n");
                  }
                else {
                  
    $n++;
                  }
                }
              if(
    is_dir($ff)) {
                  
    $fflink $ff;
                if (
    substr($ff,0,2) == "./"$fflink substr($ff,2);
                  echo 
    '<li><a href="'.$page.'?'.urlencode($fflink).'"'."><b>$f</b></a></li>\n";
                global 
    $dir;
                if (
    $ff == $dir$skipimagesnext 0;
                else 
    $skipimagesnext 1;
                if (
    $skipimages == 2$skipimagesnext 2;
                if (
    $skipimages == 3$skipimagesnext 3;
                
    checkDir($ff,$skipimagesnext);
                }
            }
            if (
    $n != "") echo "($n images)\n";
            echo(
    '</ul></div>');
          }

        
    $uri explode("?",$_SERVER['REQUEST_URI'],2);
        
    $dir urldecode($uri[1]);
        if(
    is_dir($dir)) {
            
    checkDir($dir);
            if(
    strpos($dir,"/") !== FALSE) {
                
    $updir "?".substr($dir,0,strrpos($dir,"/"));
                echo 
    '<a href="'.$page.$updir.'">^up^</a><br>'."\n";
                }
            echo 
    '<a href="'.$page.'">Top</a>'."\n";
            }
        else if(
    $dir == "all"checkDir(".",2);
        else if(
    $dir == "none"checkDir(".",3);
        else 
    checkDir(".");
        echo 
    '<a href="'.$page.'?none">Collapse All</a>'."\n";
        echo 
    '<a href="'.$page.'?all">Expand All</a>'."\n";
        
    ?>
      </body>
    </html>
    Updated test page: http://ci-pro.com/truthandlies/images/index.php

    Everything works.
    Images and subdirectories display within directories.
    Added "expand all" and "collapse all" links.
    Added numbers showing how many images a non-expanded subdirectory contains.
    Did some work on the layout so it is visually clear. (And the numbers work now.)


    No work on making the images pre-rendered. Not sure if this makes sense. (doing an if and checking if the image has an existing thumbnail and if not, creating one, seems like a bit much at the moment. Maybe....)

    No support for non-jpegs. Not yet. Easy later, though.


    I'm really liking it.
    Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  2. #12
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    Ok, now .jpg, .jpe, .jpg, .gif, and .png work, with easy addition for more filetypes, though I'm not sure what more would be supported by the GD library as is.
    Index.php
    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <title>Image Browser</title>
        <style type="text/css">
          ul.dirlist, ul.dirlist li {
            list-style-type: none;
          }
          a {
              color: #0000FF;
          }
          div.border {
          border-left-style: solid;
          border-bottom-style: solid;
          border-color: #000066;
          border-width: thin;
          }
        </style>
      </head>
      <body bgcolor="#000000" text="#0000FF">
        <?php
          $page 
    substr($_SERVER['SCRIPT_NAME'],(strrpos($_SERVER['SCRIPT_NAME'],"/")+1));
          function 
    checkDir($c,$skipimages=0) {
            echo(
    '<div class="border"><ul class="dirlist">');
            
    $d opendir($c);
            while(
    $f readdir($d)) {
              if(
    strpos($f'.') === 0) continue;
            
    $imagestypes = array(".jpg",".jpe",".jpeg",".gif",".png");
              foreach (array(
    ".jpg",".jpe",".jpeg",".gif",".png") as $imageext) {
                if (
    strtolower(substr($f,(strlen($f)-strlen($imageext)))) == $imageext) {
                
    $imageextok 1;
                break;
                  }
               }  
    $ff $c '/' $f;
              
              if (
    $imageextok == && $skipimages != 3) {
                  if (
    $skipimages != 1) {          
                  
    $fff '<img src="thumbnail.php?image='.urlencode($ff).'" border="">';
                  echo(
    '<a href="' $ff '">' $fff '</a>'."\n");
                  }
                else {
                  
    $n++;
                  }
                }
              if(
    is_dir($ff)) {
                  
    $fflink $ff;
                if (
    substr($ff,0,2) == "./"$fflink substr($ff,2);
                  echo 
    '<li><a href="'.$page.'?'.urlencode($fflink).'"'."><b>$f</b></a></li>\n";
                global 
    $dir;
                if (
    $ff == $dir$skipimagesnext 0;
                else 
    $skipimagesnext 1;
                if (
    $skipimages == 2$skipimagesnext 2;
                if (
    $skipimages == 3$skipimagesnext 3;
                
    checkDir($ff,$skipimagesnext);
                }
            }
            if (
    $n != "") echo "($n images)\n";
            echo(
    '</ul></div>');
          }

        
    $uri explode("?",$_SERVER['REQUEST_URI'],2);
        
    $dir urldecode($uri[1]);
        if(
    is_dir($dir)) {
            
    checkDir($dir);
            if(
    strpos($dir,"/") !== FALSE) {
                
    $updir "?".substr($dir,0,strrpos($dir,"/"));
                echo 
    '<a href="'.$page.$updir.'">^up^</a><br>'."\n";
                }
            echo 
    '<a href="'.$page.'">Top</a>'."\n";
            }
        else if(
    $dir == "all"checkDir(".",2);
        else if(
    $dir == "none"checkDir(".",3);
        else 
    checkDir(".");
        echo 
    '<a href="'.$page.'?none">Collapse All</a>'."\n";
        echo 
    '<a href="'.$page.'?all">Expand All</a>'."\n";
        
    ?>
      </body>
    </html>
    thumbnail.php
    PHP Code:
    <?php
    // The file
    if ($_GET['image'] == "") die('Image Does Not Exist');
    $filename urldecode($_GET['image']);
    foreach (array(
    ".jpg",".jpe",".jpeg",".gif",".png") as $imageext) {
        
    $extn++;
        if (
    strtolower(substr($filename,(strlen($filename)-strlen($imageext)))) == $imageext) {
        
    $imageextok 1;
        break;
            }
        }
    if(
    $imageextok != 1) die('Image Filetype Incorrect');

    // Set a maximum height and width
    $width 200;
    $height 200;


    // Get new dimensions
    if (@getimagesize($filename)) list($width_orig$height_orig) = getimagesize($filename);
    else die(
    'Image Filetype Incorrect.');

    $ratio_orig $width_orig/$height_orig;

    if (
    $width/$height $ratio_orig) {
       
    $width $height*$ratio_orig;
    } else {
       
    $height $width/$ratio_orig;
    }

    // Make image

    if ($extn == || $extn == || $ext ==3) {
        if (@
    imagecreatefromjpeg($filename)) $image imagecreatefromjpeg($filename);
        }
    else if (
    $extn == 4) {
        if (@
    imagecreatefromgif($filename)) $image imagecreatefromgif($filename);
        }
    else if (
    $extn == 5) {
        if (@
    imagecreatefrompng($filename)) $image imagecreatefrompng($filename);
        }
    if (!isset(
    $image)) die('Image Filetype Incorrect.');


    // Resample
    $image_p imagecreatetruecolor($width$height);
    imagecopyresampled($image_p$image0000$width$height$width_orig$height_orig);


    // Content type
    header('Content-type: image/jpeg');
    // Output
    imagejpeg($image_pnull30);

    ?>
    NOTE: Make sure that the lists (arrays) of filetypes match in both files, or there will be inconsistances.
    Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  3. #13
    Join Date
    Sep 2005
    Posts
    882
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default

    Instead of checking the extension why not use getimagesize()? It returns the image type also(despite the name).Why not cache the thumbnails? Use md5_file on the original and generate the thunmnail name off of that. Then only create a file if the hash isn't found.

  4. #14
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    md5_file is a good idea. Interesting.
    How about deleting old thumbnails if the images don't exist any more? That seems awfully hard to go about. Sure, not a huge issue. But... yeah.
    I'll think about this.

    getimagesize has filetype too? Intersting.
    Looking at the function on php.net.... strange. But seems useful. I'll need to make it ignore PSD/SWF/etc.... but... cool.
    I'll try to add that soon.
    Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  5. #15
    Join Date
    Aug 2006
    Posts
    239
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Gallery
    Code:
    <?php
    		$path = $_GET['path'];
    
    /*sanity check for breakout attempt, plus remove if path gives... no path*/
    if (($path == ".") || ($path == "/")) unset($path);
    	if (strpos($path, "/../") !== false || 
    		strpos($path, "../") === 0) $path = false;
    	if ($path) $path = stripslashes($path);
    
    	include "gallery.conf";
    /* dangerous, uncomment when you know what you're doing
    	if (!isset($masterpath)) $masterpath = getcwd();
    */
    	include "messages.txt";
            /* http://ftp.id.uw.edu.pl/pub/text/gallery/messages.txt */
    
    	include "$headername";
    
    	if (!is_dir("$masterpath/$path")) {
    		echo "
    <div class=\"bigtitle\" style=\"text-align: center\">Directory unreadable</div>
    <hr />
    ";
    		unset($path);
    	};
    
    	if ($path) {
    		$pwd = "$masterpath/$path";
    		if (dirname("$pwd") != $realpath) {
    			$link = "?path=".dirname("$path");
    		}
    	} else { 
    		$pwd = $masterpath;
    		$link="";
    	}
    
    	$dir_handle = opendir("$pwd");
    
    	$f = 1; $d = 1;
    
    	for ($x = 1; $x < 2048; $x++) {
    		$element = readdir($dir_handle);
    		if (($element) && ($element != ".")) {
    			if (is_dir("$pwd/$element")) {
    				$dirs[$d] = $element;
    				$d++;
    			} else {
    				if (getimagesize("$pwd/$element"))
    					$files[$f] = $element;
    				$f++;
    			}
    		}
    	}
    
    	if ($files) {
    		sort($files);
    		reset($files);
    	}
    
    	if ($dirs) {
    		sort($dirs);
    		reset($dirs);
    	}
    
    	$d = 0; $f = 0;
    
    	$mypath = (isset($path)) ? "$path/" : "";
    
    	for ($x = 1; $x <= (sizeof($dirs) + sizeof($files)); $x++) {
    		unset($name, $filename, $title, $size, $mtime, $myname, $mywidth, $myheight, $dimensions, $status);
    
    
    	if ($dirs[$d] && (!$done)) {
    			/* what to do with parent dirs*/
    		if ($dirs[$d] == "..") {
    			$filename = "..";
    			$title = $goup;
    			$dirtype = $parentdir;
    			if ($path) $name = "document.location.href = '$link'";
    			else $name = ""; /* or real link outside gallery */
    		} else {
    			$name = "document.location.href = '?path=$mypath".addcslashes("$dirs[$d]", "\"\'")."'";
    			$title = $filename = $dirs[$d];
    			$dirtype = $directory;
    		}		
    		$thumb = "dir.php";
    		$mtime = date ("Y:m:d G:i", filemtime("$pwd/$dirs[$d]"));
    		$myname = ($dirs[$d] == "..") ? basename(dirname("/var/ftp/pub/$path")) : addcslashes("$filename", "\'\"");
    		$d++;
    		
    		$done = 0;
    	} else {
    		$done = 1;
    	}
    
    	if ($done) {
    		list($mywidth, $myheight, $garbage) = getimagesize("$pwd/$files[$f]");
    		$name = "javascript:location.href = 'pic.php?img=".addcslashes("$mypath$files[$f]", "\'\"")."';";
    		$thumb = "pic.php?img=$mypath$files[$f]&amp;thumb=1";
    
    		if (!$files[$f]) break;
    
    		$f++;
    	}
    
    	if ($name) {
    		$islink = is_link("$pwd/$filename");
    		$pathinfo = pathinfo($filename);
    		$pathinfo = $pathinfo[extension];
    		if (strlen($filename) - strlen($pathinfo) >= 15) {
    			$filename = substr($filename, 0, 11)."... .".$pathinfo;
    		}
    
    		if ($islink) $filename = "<span style=\"color: #ff6; font-style: italic\">$filename</span>";
    		echo "
    	<div class=\"imgholder\" title=\"$title\"
    		onmouseover=\"setcolor(this, '$hovercolor'); setcolor('title$x', '$hovertitle');\"
    		onmouseout=\"setcolor(this, '$normalcolor'); setcolor('title$x', '$normaltitle');\"
    		onmousedown=\"setcolor(this, '$activecolor'); setcolor('title$x', '$activetitle');\"
    		onclick=\"$name\">
    	<div style=\"display: table-row\">
    	<div class=\"imageframe\">
    <!--[if IE]>
    	<table cellspacing=0 cellpadding=0><tr><td height=\"$maxheight\">
    <![endif]-->
    	<img";
    		if ($done) {
    			echo " class=\"border\"";
    		} else {
    			echo " style=\"border: 0\"";
    		}
    		echo "
    		src=\"$thumb\" 
    		title=\"$title\" alt=\"$title\"/>
    <!--[if IE]>
    	</td></tr></table>
    <![endif]-->
    	</div>
    	</div>
    	<div style=\"display: table-row\">
    	<div class=\"imgTitle\" id=\"title$x\">
    	$filename
    	</div>
    	</div>
    	</div>
    ";
    	}
    }
    
    include "$footername";
    ?>
    and simple config for it:

    Code:
    <?
    	$masterpath = "/var/ftp/pub/pictures";
    	/* jail sript to this directory, do not allow parent */
    	$cache= "/var/cache/apache/galeria";
    	/* where to keep thumbnail images */
    	$maxwidth = $maxheight = 150;
    	/* size of thumbnails, you can also use $maxwidth = ($small) 40 : 150; for example */
    
    	$lang = "pl";
    	/*feature for language*/
    
    	/* header and footer name*/
    	$headername = "./myheader.php";
    	$footername = "./myfooter.php";
    ?>
    Needs more customising, but out of the box, it should work just fine

    http://ftp.id.uw.edu.pl/pub/pictures/ the thing in action.
    http://ftp.id.uw.edu.pl/pub/texts/gallery.tgz the gallery in such form, packed and ready to use
    Last edited by ItsMeOnly; 10-21-2006 at 07:29 PM.

  6. #16
    Join Date
    Aug 2006
    Posts
    239
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    My old faithful "image handler for galleries

    Code:
    <?php
    
    /* what we can handle */
    $imgtype = array(1  => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp', 'tiff', 
    	'tiff', 'jpc', 'jp2', 'jpx', 'jb2', 'swc', 'iff', 'wbmp', 'xbm');
    
    $img   = stripslashes($_GET['img']);
    $thumb = $_GET['thumb'];
    $small = $_GET['small'];
    /* we can generate two sorts of thumbs basically, big and small ones- like two step preview */
    
    $sm = ($small) ? "sm_" : "";
    /* append to thumbnail filename */
    
    $type = $_GET['type'];
    /* about this later, nifty xsl safeguard */
    
    /* what we do for images with question mark in name? first strip it, then get it back! */
    if (isset($img)) $img = str_replace("=63", "?", $img);
    else die("No image set for displaying");
    
    function updateThumb() {
    	global $imgtype, $mimetype, $img, $thumbnail, 
    		$maxwidth, $maxheight, $width, $height;
    
    	if ($width > $maxwidth) {
    		$newwidth = $maxwidth;
    		(int) $newheight = ( $maxwidth / $width ) * $height;
    	} else {
    		$newwidth = $width;
    		$newheight = $height;
    	}
    
    	if ($newheight > $maxheight) {
    		$newheight = $maxheight;
    		(int) $newwidth = ( $maxheight / $height ) * $width;
    	};
    
    	$newimage = imagecreatetruecolor($newwidth, $newheight);
    
    	switch($mimetype) {
    		case 1:
    			$content = @imagecreatefromgif("$img");
    			break;
    		case 2:
    			$content = @imagecreatefromjpeg("$img");
    			break;
    		case 3:
    			$content = @imagecreatefrompng("$img");
    			break;
    		case 7:
    		case 8:
    			$content = @imagecreatefromtiff("$img");
    			break;
    		default:
    			/* change me!*/
    			$content = shell_exec("/usr/bin/convert $img png:-");
    			$content = imagecreatefromstring("$content");
    			break;
    	};
    
    	if ($content) {
    		imagecopyresampled( $newimage, $content, 0, 0, 0, 0, 
    			$newwidth, $newheight, $width, $height );
    		imagedestroy($content);
    	};
    
    	imagejpeg($newimage, $thumbnail, 92);
    	imagedestroy($newimage);
    }		
    
    /*edit me */
    function doHTML($img, $base) {
    	include "messages.txt";
    	global $masterpath, $headername, $footername;
    
    	$tmpimg = "$masterpath/$img";
    	list($width, $height, $mimetype) = getimagesize("$tmpimg");
    	$exifdata = @exif_read_data("$tmpimg", "EXIF");
    
    	include "$headername";
    
    	echo "
    	<div id=\"imagearea\">
    	<img src=\"".$_SERVER['PHP_SELF']."?img=$img&amp;type=$base\"
    		style=\"margin: auto\" title=\"$img\" alt=\"$img - full size\"/>
    	</div>
    	<div class=\"data\" id=\"imageData\">";
    
    	/* if you have any information about image in accompanying text file...*/
    	if (file_exists("$masterpath/$img.txt")) {
    		$myText = file_get_contents("$masterpath/$img.txt");
    		$myText = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
    	    		"<a href=\"\\0\">\\0</a>", $myText);
    		$myText = nl2br($myText);
    		echo "<div class=\"normaltext\">$myText</div><hr />";
    		unset($myText);
    	}
    
    	echo "
    	<b class=\"label\" style=\"width: 100%\">$tmpimg</b><br />
    	$filesize: " . filesize($tmpimg) . " $bytes, $img_res $width"."x$height<br />";
    	
    	echo "$Modified (GMT): " . date("Y:m:d G:i",  filemtime($tmpimg));
    
    	/* exif time- replace "$img_" strings with plaintext, normally I'm using "localised" text */
    	if ($exifdata) {
    		if ($exifdata[ExposureTime]) {
    			$exposuretime = split("/", $exifdata[ExposureTime]);
    			if (($exposuretime[0] == 10) &&
    				($exposuretime[1] % 10 == 0)) {
    				$exposuretime = "1/" . ($exposuretime[1] / 10);
    			} else if ($exposuretime[0] % $exposuretime[1] == 0) {
    				$exposuretime = ($exposuretime[0] / $exposuretime[1]);
    			} else $exposuretime = $exifdata[ExposureTime];
    		}
    		echo "<br />
    	EXIF: $ctime: ";
    		echo ($exifdata[DateTime]) ? $exifdata[DateTime] : $exifdata[DateTimeOriginal];
    		echo "<br />
    	EXIF: $img_ores: $exifdata[ExifImageWidth]x$exifdata[ExifImageLength],
    	DPI: x=".(int) $exifdata[XResolution]." y=".(int) $exifdata[YResolution]."<br />
    	EXIF: $img_caminfo: $exifdata[Make] $exifdata[Model]<br />";
    
    		if (isset($exifdata[ExposureBiasValue])) {
    			$tmpnum = split("/", "$exifdata[ExposureBiasValue]");
    			$tmpevbias = $tmpnum[0] / $tmpnum[1];
    		}
    
    		if (!isset($shortexif)) {
    			echo "
    	EXIF: ";
    			if (isset($exifdata[ExposureProgram])) {
    				$tmpnum = $exifdata[ExposureProgram];
    				echo "$img_exposureprog: $img_exposureprogt[$tmpnum], ";
    			}
    
    			echo "$img_exposuretime: $exposuretime"."s,<br />";
    
    			if (isset($tmpevbias)) printf("EXIF: %s: %+.2f, ", $img_evbias, $tmpevbias);
    			echo "ISO $exifdata[ISOSpeedRatings];<br />";
    
    			if (isset($exifdata[Flash])) {
    				$tmpnum = $exifdata[Flash];
    				echo "
    	EXIF: $img_flasht[$tmpnum];<br />";
    			}
    
    			echo "
    	EXIF: $img_focallength: ". ($exifdata[FocalLength] / 10) . "mm,
    	$img_aperture: ". $exifdata[COMPUTED][ApertureFNumber] .", 
    	$img_digitalzoom: ". ($exifdata[DigitalZoomRatio] / 100). "x;<br />";
    		} else {
    			echo "EXIF: ISO $exifdata[ISOSpeedRatings], ";
    			if (isset($tmpevbias)) printf("EV: %+.2f, ", $tmpevbias);
    			if ($exposuretime) echo "t=$exposuretime, ";
    			echo $exifdata[COMPUTED][ApertureFNumber] .", f=".
    				($exifdata[FocalLength] / 10) . "mm, D=".
    				($exifdata[DigitalZoomRatio] / 100). "x.";
    		}
    	}
    	echo "</div>";
    	include "$footername";
    }
    
    
    /* this is cross-site linking safeguard, also simple mean to use the same script for multiple galleries */
    $query_string = explode("?", $_SERVER['HTTP_REFERER']);
    $basename = basename($query_string[0],
    	stristr($query_string[0], ".htm"));
    unset($query_string);
    
    if (!isset($headername)) $headername = "header.inc";
    if (!isset($footername)) $footername = "footer.inc";
    
    if (!file_exists("$basename.conf")) {
    	if (!$type) {
    		include $headername;
    		echo "
    	<div style=\"text-align:left\">
    	<h2 class=\"bigtitle\">Configuration file for viewer is not present or<br />
    	configuration directive has not been specified.<p />
    	Cannot continue - bailing out.</h2>
    	Called from $basename (".stristr($_SERVER['HTTP_REFERER'], ".htm") ."
    	</div>";
    		include $footername;
    		exit();
    	} else {
    		include "$type.conf";
    		$myfile = "$type.conf";
    	}
    } else {
    	include "$basename.conf";
    	$myfile = "$basename.conf";
    }
    
    
    $scaling_needed = false;
    $update_needed = false;
    
    if ($thumb) {
    	$tmpimg = $img;
    	$img = "$masterpath/$img";
    
    	$mysize = filesize("$img");
    	$thumbnail = "$cache/$sm$tmpimg-$mysize";
    
    	if (getimagesize("$img")) {
    		list($width, $height, $mimetype) = getimagesize("$img");
    
    		if (($width > $maxwidth) || ($height > $maxheight))
    		$scaling_needed = true;
    	} else {
    		header("HTTP/1.0 404 Not found");
    		die();
    	}
    
    	$dirpath = dirname($thumbnail);
    	if (!is_dir($dirpath)) mkdir($dirpath);
    
    	if ((!file_exists($thumbnail)) || (filemtime($img) > filemtime($thumbnail)) ||
    		(filemtime($_SERVER[SCRIPT_FILENAME]) > filemtime($thumbnail)) ||
    		(filemtime($myfile) > filemtime($thumbnail))) {
    		$update_needed = true;
    	}
    
    	if ($scaling_needed) {
    		if ($update_needed) updateThumb();
    		header("Content-type: image/jpeg");
    		header('Content-transfer-encoding: binary');
    		readfile($thumbnail);
    	} else {
    		if (getimagesize("$img")) {
    			header("Content-type: image/$imgtype[$mimetype]");
    			header('Content-transfer-encoding: binary');
    			header('Content-length: '.filesize($img));
    			readfile($img);
    		} else {
    			header("HTTP/1.0 404 Not found");
    			die();
    		}
    	}
    } else {
    	if (!file_exists("$masterpath/$img")) {
    		$mypath = dirname("$img");
    		header("Location: http://rambo.id.uw.edu.pl/viewer.html?path=$mypath");
    	} else {
    
    /* S A F E G U A R D ! ! ! */
    		if ($type) {
    			if ($_SERVER['HTTP_REFERER'] && !isset($_GET[wrap])) {
    				include "$type.conf";
    				$img = "$masterpath/$img";
    				if(@getimagesize("$img")) {
    					list($garbage, $garbage, $mimetype) = getimagesize("$img");
    
    					header("Content-type: image/$imgtype[$mimetype]");
    					header('Content-transfer-encoding: binary');
    					header('Content-length: '.filesize($img));
    					readfile($img);
    				} else {
    					header("HTTP/1.0 404 Not found");
    					die();
    				}
    			} else {
    				doHTML($img, $type);
    			}
    		} else {
    			if ($_SERVER['HTTP_REFERER']) {
    				doHTML($img, $basename);
    			}
    		}
    	}
    };
    ?>
    syntax: ?img=path/image&type=config&thumb=[0|1]&small=[0|1]

    About the safeguard, and multipurpose use: normally picture/thumbviewer was guessing from refering URL what kind of config (look, size of thumbnails, cache, and path) it should use, you can remove the "basename" stuff (bright red stuff at the end) and replace it with include "gallery.conf", if you're not using alternate layouts, sizes, etc. Also, if you're just for the displaying images and generating thumbnails, you could simply replace the conditional statement "if ($type)" from the S A F E G U A R D stuff.

    The dark red section is for the "wrapper", basically this thing calls itself recursively, first generating a web page, wrapping it in html, and displaying file information, and then calling itself again, this time generating real image.

    the original name, as used with conjunction with gallery above is pic.php
    Last edited by ItsMeOnly; 10-21-2006 at 07:22 PM.

  7. #17
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    Ok. Updates:
    1. getimagesize now used to check image type in both pages; more efficient structure.
    2. md5_file and storing thumbnails now in place.

    Notes/problems:
    1. The directory "_thumbs" had to be created manually. What's the easy way to do this in PHP? (though, including it in the script does seem like one extra thing to run each time, if the creation need only be once, but... makes sense... why not.)
    2. Due to the strange way that imagejpeg($image,$filename,$quality) works, when it creates an image and stores it as $filename, the output is a textual representation of the filename, not the image. However, if the middle (filename) value is left null (as it is when displaying if the image IS found), then the output is fine. This means one load without seeing the image, but the image loads from then on. This would be fine if the admin wanted to run the script each time a new image was added... not that big a hassle. But.... would be nice to fix. I could do an output buffer and avoid the error that way, then output the new image, but that seems a pain. Any ideas here? I could also just create the image differently, as a file, not using a GD function. But again, doesn't seem like it makes sense. There must be something wrong with this function.

    Here's the code:
    INDEX.PHP
    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <title>Image Browser</title>
        <style type="text/css">
          ul.dirlist, ul.dirlist li {
            list-style-type: none;
          }
          a {
              color: #0000FF;
          }
          div.border {
          border-left-style: solid;
          border-bottom-style: solid;
          border-color: #000066;
          border-width: thin;
          }
        </style>
      </head>
      <body bgcolor="#000000" text="#0000FF">
        <?php
          $page 
    substr($_SERVER['SCRIPT_NAME'],(strrpos($_SERVER['SCRIPT_NAME'],"/")+1));
          function 
    checkDir($c,$skipimages=0) {
            echo(
    '<div class="border"><ul class="dirlist">');
            
    $d opendir($c);
            while(
    $f readdir($d)) {
              if(
    strpos($f'.') === 0) continue;
              
    $ff $c '/' $f;
              if (@
    getimagesize($ff)) {
                
    $imginfo getimagesize($ff);
                }
              if (
    $imginfo[2] == || $imginfo[2] == || $imginfo[2] == 3) {
                
    $imgtypeok 1;
                }          
              if (
    $imgtypeok == && $skipimages != 3) {
                  if (
    $skipimages != 1) {          
                  
    $fff '<img src="thumbnail.php?image='.urlencode($ff).'" border="">';
                  echo(
    '<a href="' $ff '">' $fff '</a>'."\n");
                  }
                else {
                  
    $n++;
                  }
                }
              if(
    is_dir($ff) && substr($ff,(strlen($ff)-7)) != "_thumbs") {
                  
    $fflink $ff;
                if (
    substr($ff,0,2) == "./"$fflink substr($ff,2);
                  echo 
    '<li><a href="'.$page.'?'.urlencode($fflink).'"'."><b>$f</b></a></li>\n";
                global 
    $dir;
                if (
    $ff == $dir$skipimagesnext 0;
                else 
    $skipimagesnext 1;
                if (
    $skipimages == 2$skipimagesnext 2;
                if (
    $skipimages == 3$skipimagesnext 3;
                
    checkDir($ff,$skipimagesnext);
                }
            }
            if (
    $n != "") echo "($n images)\n";
            echo(
    '</ul></div>');
          }

        
    $uri explode("?",$_SERVER['REQUEST_URI'],2);
        
    $dir urldecode($uri[1]);
        if(
    is_dir($dir)) {
            
    checkDir($dir);
            if(
    strpos($dir,"/") !== FALSE) {
                
    $updir "?".substr($dir,0,strrpos($dir,"/"));
                echo 
    '<a href="'.$page.$updir.'">^up^</a><br>'."\n";
                }
            echo 
    '<a href="'.$page.'">Top</a>'."\n";
            }
        else if(
    $dir == "all"checkDir(".",2);
        else if(
    $dir == "none"checkDir(".",3);
        else 
    checkDir(".");
        echo 
    '<a href="'.$page.'?none">Collapse All</a>'."\n";
        echo 
    '<a href="'.$page.'?all">Expand All</a>'."\n";
        
    ?>
      </body>
    </html>
    thumbnail.php
    PHP Code:
    <?php
    // The file
    if ($_GET['image'] == "") die('Image Not Specified');
    $filename urldecode($_GET['image']);
    if (@
    getimagesize($filename)) {
        
    $imginfo getimagesize($filename);
        }
    if (
    $imginfo[2] != && $imginfo[2] != && $imginfo[2] != 3) {
        die(
    'Image Filetype Incorrect');
        }
    //echo md5_file($filename)."jpg;".$filename."\n";
    if (@getimagesize("_thumbs/".md5_file($filename).".jpg") !== FALSE) {
        
    // Content type
        
    header('Content-type: image/jpeg');
        
    // Output
        
    $thumb imagecreatefromjpeg("_thumbs/".md5_file($filename).".jpg");
        
    imagejpeg($thumbnull50);
        }
    else {
        
    // Set a maximum height and width
        
    $width 200;
        
    $height 200;
        
    // Get new dimensions
        
    list($width_orig$height_orig) = array($imginfo[0],$imginfo[1]);
        
    $ratio_orig $width_orig/$height_orig;
        if (
    $width/$height $ratio_orig) {
            
    $width $height*$ratio_orig;
        } else {
            
    $height $width/$ratio_orig;
        }
        
    // Make image
        
    if ($imginfo[2] == 1) {
            if (@
    imagecreatefromgif($filename)) $image imagecreatefromgif($filename);
            }
        else if (
    $imginfo[2] == 2) {
            if (@
    imagecreatefromjpeg($filename)) $image imagecreatefromjpeg($filename);
            }
        else if (
    $imginfo[2] == 3) {
            if (@
    imagecreatefrompng($filename)) $image imagecreatefrompng($filename);
            }
        if (!isset(
    $image)) die('Image Filetype Incorrect.');
        
    // Resample
        
    $thumb imagecreatetruecolor($width$height);
        
    imagecopyresampled($thumb$image0000$width$height$width_orig$height_orig);
        
    // Content type
        
    header('Content-type: image/jpeg');
        
    // Output
        
    imagejpeg($thumb"_thumbs/".md5_file($filename).".jpg"50);
        }

    ?>
    Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  8. #18
    Join Date
    Aug 2006
    Posts
    239
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by djr33
    1. The directory "_thumbs" had to be created manually.
    mkdir();
    2. Due to the strange way that imagejpeg($image,$filename,$quality) works, when it creates an image and stores it as $filename, the output is a textual representation of the filename, not the image. However, if the middle (filename) value is left null (as it is when displaying if the image IS found), then the output is fine.
    That is no strange, the generated jpeg should be valid format FILE, by leaving "filename" empty, you ask imagejpeg to output to "stdout", omitting the saving the stream to disk.

    However I see you are going to regenerate the thumbs manually if file content changes? right?
    Last edited by ItsMeOnly; 10-27-2006 at 05:12 PM.

  9. #19
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    mkdir. Easy. Thanks.

    Ah. Ok, so I can just output the image that was placed there, then? I thought that calling imagejpeg() twice would screw things up.

    No need to update anything manually. md5_file takes the contents of the image and creates a thumbnail named [md5].jpg. That way, if two images are the same, they can use the same thumbnail (saving a small bit of space, perhaps), and will allow updates to occur.... if the image (even with the same name) is updated, the file_md5() result won't match any of the thumbnails, so it will be updated.

    There are a couple problems still happening that I will look into. (I think it stopped skipping non-image files once I used getimagesize, though not sure why, and a couple other things.)

    I should also give a BIG warning--- the host suspended my account due to overstressing the server with this. I was converting about 600 thumbnails from about 900mb of photos.
    The host is back up (since it's through someone I know, not just a normal hosting service), but it's worth knowing... this can really stress the processor.
    I don't know any figures/numbers on it.... but.... yeah.
    Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  10. #20
    Join Date
    Aug 2006
    Posts
    239
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Tell me about it- I once pulled 132 thumbnails to regenerate (just dragging my mouse over will trigger the regeneration)- so I pulled it out... well, a screen for you of machine load.


    Normally the graph rarely goes beyond 1,2 lines (under heavy load, like compiling, or playing games). Needless to say, the load of 63 successfully _halted_ the server for about 5 minutes.

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
  •