[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

Need help fixing (or finding) PHP-based thumbnail image generating script

Posted on 2009-05-18
6
Medium Priority
?
316 Views
Last Modified: 2013-12-13
I'm having a really hard time getting the attached PHP-based thumbnail image generating script to work on my windows-based shared hosting account.  

The errors that I'm getting when I try to apply the createthumb() function -- using 100% valid image resources --- are as follows:

Notice: Undefined offset: 1 in D:\Inetpub\antiqueplace\webauction\upload\thumbnail_generator.php on line 92

Notice: Undefined variable: tmparr
Notice: Undefined variable: src_img
Warning: imagesx(): supplied argument is not a valid Image resource
Warning: imagesy(): supplied argument is not a valid Image resource
Notice: Undefined variable: src_img
Warning: imagecopyresampled(): supplied argument is not a valid Image resource
Warning: imagedestroy(): supplied argument is not a valid Image resource

(etc..)

It's confusing because I've gotten this script to work without any problems several times already (on the same shared hosting environment) .. yet for some reason I can't get the script to work properly in this case. Why is this script failing? How can I fix it?

If anyone knows of a better way for me to create thumbnail images using PHP ... I'd be open to replacing what I've got with it.  

Thanks,
- Yvan


<?php 
$imagefolder='.';
$thumbsfolder='.';
$pics=directory($imagefolder,"jpg,JPG,JPEG,jpeg,png,PNG");
$pics=ditchtn($pics,"tn_");
if ($pics[0]!="")
{
	foreach ($pics as $p)
	{
		createthumb($p,"tn_".$p,150,150);
	}
}
 
/*
	Function ditchtn($arr,$thumbname)
	filters out thumbnails
*/
function ditchtn($arr,$thumbname)
{
	foreach ($arr as $item)
	{
		if (!preg_match("/^".$thumbname."/",$item)){$tmparr[]=$item;}
	}
	return $tmparr;
}
 
/*
	Function createthumb($name,$filename,$new_w,$new_h)
	creates a resized image
	variables:
	$name		Original filename
	$filename	Filename of the resized image
	$new_w		width of resized image
	$new_h		height of resized image
*/	
function createthumb($name,$filename,$new_w,$new_h)
{
	$system=explode(".",$name);
	if (preg_match("/jpg|jpeg/",$system[1])){$src_img=imagecreatefromjpeg($name);}
	if (preg_match("/png/",$system[1])){$src_img=imagecreatefrompng($name);}
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	if ($old_x > $old_y) 
	{
		$thumb_w=$new_w;
		$thumb_h=$old_y*($new_h/$old_x);
	}
	if ($old_x < $old_y) 
	{
		$thumb_w=$old_x*($new_w/$old_y);
		$thumb_h=$new_h;
	}
	if ($old_x == $old_y) 
	{
		$thumb_w=$new_w;
		$thumb_h=$new_h;
	}
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
	if (preg_match("/png/",$system[1]))
	{
		imagepng($dst_img,$filename); 
	} else {
		imagejpeg($dst_img,$filename); 
	}
	imagedestroy($dst_img); 
	imagedestroy($src_img); 
}
 
/*
        Function directory($directory,$filters)
        reads the content of $directory, takes the files that apply to $filter 
		and returns an array of the filenames.
        You can specify which files to read, for example
        $files = directory(".","jpg,gif");
                gets all jpg and gif files in this directory.
        $files = directory(".","all");
                gets all files.
*/
function directory($dir,$filters)
{
	$handle=opendir($dir);
	$files=array();
	if ($filters == "all"){while(($file = readdir($handle))!==false){$files[] = $file;}}
	if ($filters != "all")
	{
		$filters=explode(",",$filters);
		while (($file = readdir($handle))!==false)
		{
			for ($f=0;$f<sizeof($filters);$f++):
				$system=explode(".",$file);
				if ($system[1] == $filters[$f]){$files[] = $file;}
			endfor;
		}
	}
	closedir($handle);
	return $files;
}
?>

Open in new window

0
Comment
Question by:egoselfaxis
  • 4
  • 2
6 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24416307
This is the code I use for "index.php" in photo directories.  It makes thumbnails if they do not already exist.  Please look it over and post back here if you have any questions.

Best regards, ~Ray
<?php // RAY_photo_directory.php
error_reporting(E_ALL);
 
// ALLOWABLE WIDTH AND HEIGHT
DEFINE('W', 360);
DEFINE('H', 360);
 
// THUMBNAIL PREFIX
DEFINE('T', "tn_");
 
// GET THE NAMES OF ALL THE FILES
$dir = scandir(getcwd());
 
// WINNOW THE CHAFF
foreach ($dir as $ptr => $jpg)
{
    if (!eregi(".jpg$", $jpg))
    {
        unset($dir[$ptr]);
    }
}
 
// MAKE THUMBNAILS
$prefix_regex = '^' . T;
foreach ($dir as $ptr => $jpg)
{
// IF THIS IS A THUMBNAIL, SKIP IT
    if (eregi("$prefix_regex", $jpg))
    {
        unset ($dir[$ptr]);
        continue;
    }
 
// IF WE ALREADY HAVE A THUMBNAIL
    $thumb = T . $jpg;
    if (!in_array($thumb, $dir))
    {
        $imageblob = create_right_size_image($jpg);
        imagejpeg($imageblob, $thumb);
    }
}
 
// WE HAVE ADDED TO THE DIRECTORY - REGET THE NAMES OF ALL THE FILES
$dir = scandir(getcwd());
 
// WINNOW THE CHAFF - KEEP ONLY THE ORIGINAL JPG FILE NAMES
$prefix_regex = '^' . T;
foreach ($dir as $ptr => $jpg)
{
    if ( !eregi(".jpg$", $jpg) || eregi("$prefix_regex", $jpg) )
    {
        unset($dir[$ptr]);
    }
}
 
// DISPLAY THE THUMBNAIL LINKS
foreach ($dir as $ptr => $jpg)
{
    $thumb = T . $jpg;
    echo "<br clear=\"all\" /><a href=\"$jpg\"><img src=\"$thumb\"></a>\n";
}
 
// DONE
die();
 
 
 
 
// LOCAL FUNCTIONS
 
// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{
 
// IS GD INSTALLED AT ALL?
   if (!function_exists("gd_info"))
   {
      if ($display) echo "<br/>GD NOT INSTALLED\n";
      return FALSE;
   }
 
// IF GD IS INSTALLED GET DETAILS
   $gd = gd_info();
 
// IF DISPLAY IS REQUESTED, PRINT DETAILS
   if ($display)
   {
      echo "<br/>GD DETAILS:\n";
      foreach ($gd as $key => $value)
      {
         if ($value === TRUE)  $value = 'YES';
         if ($value === FALSE) $value = 'NO';
         echo "<br/>$key = $value \n";
      }
   }
 
// RETURN THE VERSION NUMBER
   $gd_version = ereg_replace('[^0-9\.]', '', $gd["GD Version"]);;
   return $gd_version;
}
 
 
// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE
function create_right_size_image($image, $width=W, $height=H)
{
// IS GD HERE?
   $gdv = get_gd_info();
   if (!$gdv) return FALSE;
 
// GET AN IMAGE THING
   $source = imagecreatefromjpeg("$image");
 
// GET THE X AND Y DIMENSIONS
   $imageX = imagesx($source);
   $imageY = imagesy($source);
 
// IF NO RESIZING IS NEEDED
   if ( ($imageX <= $width) && ($imageY <= $height) )
   {
      return $source;
   }
 
// IF THE WIDTH IS TOO GREAT - MUST RESIZE
   if ($imageX > $width)
   {
      $tnailX = $width;
      $tnailY = (int) (($tnailX * $imageY) / $imageX );
   }
 
// IF THE HEIGHT IS TOO GREAT - MUST RESIZE
   if ($imageY > $height)
   {
      $tnailY = $height;
      $tnailX = (int) (($tnailY * $imageX) / $imageY );
   }
 
// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
   if ($gdv >= 2)
   {
// IF GD IS AT LEVEL 2 OR ABOVE
      $target = imagecreatetruecolor($tnailX, $tnailY);
      imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   } else
   {
// IF GD IS AT A LOWER REVISION LEVEL
      $target = imagecreate($tnailX, $tnailY);
      imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   }
   return $target ;
}

Open in new window

0
 

Author Comment

by:egoselfaxis
ID: 24421303
Is there any possibility of getting something a bit simpler -- perhaps something that handles the thumbnail creation for a single JPEG image?  
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 24422793
Yes.  Please read the code posted here.  That is EXACTLY what the function create_right_size_image does.
0
Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24422815
The calling sequence for that function is on lines 38 and 39.

HTH, ~Ray
        $imageblob = create_right_size_image($jpg);
        imagejpeg($imageblob, $thumb);

Open in new window

0
 

Author Comment

by:egoselfaxis
ID: 24426769
Thanks Ray!

- Yvan
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 24426815
Thanks for the points, Yvan - it's a great question! ~Ray
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

591 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question