How do I make this function work

The attached function works, from what I can gather, but I don't know how to implement it into my loop.

What I want to do is loop through every image I have in my database and plug in this function so I can make a thumbnail of each image.

So...

$query = "select * photos order by photo_date;
$query_go = mysqli_query($cxn, $query)
or die("Couldn't execute query.");
while ($query_row = mysqli_fetch_assoc($query_go))
{
extract($query_row;
....and here's where I don't know what I'm doing

The working function is attached. How do I plug it into my loop?
<?php 

     // Resize a JPG image using resampling to antialias the new image and output
     // the image to a new filename
     //
     // Parameters: $filename - the filename of the image
     //             $width - the new MAXIMUM width to resize to
     //             $height - the new MAXIMUM height to resize to
     //             $newFilePath - the new filename to output to
     //             $quality - the JPG quality. 100 is best, default is 75
     //
     function jpgResizeFrom( $filename, $width, $height, $newFilePath, $quality=75 ) { 
          if ( file_exists( $filename ) && !is_dir( $filename ) ) { 
               // Get current dimensions and calculate the best size
               list($widthOrig, $heightOrig) = getimagesize($filename);
     
               if ( $heightOrig > 0 ) {
                    
                    $ratioOrig = $widthOrig/$heightOrig;
          
                    if ( ($width/$height) > $ratioOrig)
                         $width = $height * $ratioOrig;
                    else
                         $height = $width / $ratioOrig;
          
          
                    // Resample the original image
                    //
                    $image_p = imagecreatetruecolor($width, $height);
                    $image = imagecreatefromjpeg($filename);
                    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
          
          
                    // Output to a file and clear memory of the old images
                    //
                    imagejpeg($image_p, $newFilePath, $quality);
                    imagedestroy($image_p);
                    imagedestroy($image);
     
               } 

          } // if file_exists
     } 
 

     // Directory must exist. Get a list of all objects in it which match the permitted types
     // for this directory
     //
     $width = 160;  // pixels
     $height = 100;   // pixels 
     $imageFolder = "/path/to/image/folder";
     $newFilePath = "/path/to/target/folder"; 

     $scan = scandir( $imageFolder );
     
     foreach ( $scan as $aFile ) {
          $fileParts = pathinfo( $aFile );
          $filename  = $fileParts['filename'];
          $extension = strtolower( $fileParts['extension'] );
          $origName  = "$imageFolder/$filename.$extension";
          $newName   = "$newFilePath/$filename.$extension"; 
          if ( $extension == "jpg" || $extension == "jpeg" ) {
               jpgResizeFrom( $origName, $width, $height, $newName );
          } 
     } 
 
?>

Open in new window

brucegustPHP DeveloperAsked:
Who is Participating?
 
Beverley PortlockConnect With a Mentor Commented:
Check the permissions of the files being skipped - the web server needs to be able to read them. Give them the same permissions as a file that did work.

Also, add this to the start of your script

ini_set('display_errors', 1);  error_reporting(E_ALL);

and run it again and see what error messages show up
0
 
Beverley PortlockCommented:
OK - the posted code contains two parts

<?php 

     // Resize a JPG image using resampling to antialias the new image and output
     // the image to a new filename
     //
     // Parameters: $filename - the filename of the image
     //             $width - the new MAXIMUM width to resize to
     //             $height - the new MAXIMUM height to resize to
     //             $newFilePath - the new filename to output to
     //             $quality - the JPG quality. 100 is best, default is 75
     //
     function jpgResizeFrom( $filename, $width, $height, $newFilePath, $quality=75 ) { 
          if ( file_exists( $filename ) && !is_dir( $filename ) ) { 
               // Get current dimensions and calculate the best size
               list($widthOrig, $heightOrig) = getimagesize($filename);
     
               if ( $heightOrig > 0 ) {
                    
                    $ratioOrig = $widthOrig/$heightOrig;
          
                    if ( ($width/$height) > $ratioOrig)
                         $width = $height * $ratioOrig;
                    else
                         $height = $width / $ratioOrig;
          
          
                    // Resample the original image
                    //
                    $image_p = imagecreatetruecolor($width, $height);
                    $image = imagecreatefromjpeg($filename);
                    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
          
          
                    // Output to a file and clear memory of the old images
                    //
                    imagejpeg($image_p, $newFilePath, $quality);
                    imagedestroy($image_p);
                    imagedestroy($image);
     
               } 

          } // if file_exists
     } 
 

Open in new window


The above code is the main bit you need. Put this function somewhere in your scripts. The next bit (below) is a demonstration of how to use the function.


     // Directory must exist. Get a list of all objects in it which match the permitted types
     // for this directory
     //
     $width = 160;  // pixels
     $height = 100;   // pixels 
     $imageFolder = "/path/to/image/folder";
     $newFilePath = "/path/to/target/folder"; 

     $scan = scandir( $imageFolder );
     
     foreach ( $scan as $aFile ) {
          $fileParts = pathinfo( $aFile );
          $filename  = $fileParts['filename'];
          $extension = strtolower( $fileParts['extension'] );
          $origName  = "$imageFolder/$filename.$extension";
          $newName   = "$newFilePath/$filename.$extension"; 
          if ( $extension == "jpg" || $extension == "jpeg" ) {
               jpgResizeFrom( $origName, $width, $height, $newName );
          } 
     } 
 

Open in new window


What you need is a folder that thumbnail images can be written into. You then take your big images, feed them into the resize function and you get a smaller image in the thumbnail folder. You can then display the thumbnailed image in an image tag

<img src='thumbnail/myimage.jpg' />

So in your loop you are going to extract a series of paths to images. Let us assume that you have a folder called 'thumbs' in which we can store thumbnailed (resized) images. We will assume that you want the resized images to be 160x100 pixels in size. Then it goes like this

$width = 160;  // pixels
$height = 100;   // pixels 
$newFilePath = 'thumbs';
$imageFolder = 'images';

while ($query_row = mysqli_fetch_assoc($query_go))
{
         $fileParts = pathinfo( $query_row['filepath'] );
          $filename  = $fileParts['filename'];
          $extension = strtolower( $fileParts['extension'] );
          $origName  = "$imageFolder/$filename.$extension";
          $newName   = "$newFilePath/$filename.$extension"; 
          if ( $extension == "jpg" || $extension == "jpeg" ) {
               jpgResizeFrom( $origName, $width, $height, $newName );
               echo "<a href='./$origName'><img src='$newName' /></a>";
          } 

}

Open in new window




0
 
brucegustPHP DeveloperAuthor Commented:
My code is attached and it works! Thing is, it stops after doing about 20 images. I've got over 100 photos and while it cranks out some sweet looking thumbnails, it doesn't go through all the images. I've got a little more than 20 and that's it. What am I missing? I need to loop through the entire database.
<?php



session_start(); 

if (@$_SESSION['auth'] != "yes")                   

{

header("Location: default.php");

exit();

}



include ("../carter.inc");



$cxn = mysqli_connect($host,$user,$password,$database)

or die ("couldn't connect to server");

     function jpgResizeFrom( $filename, $width, $height, $newFilePath, $quality=75 ) { 
          if ( file_exists( $filename ) && !is_dir( $filename ) ) { 
               // Get current dimensions and calculate the best size
               list($widthOrig, $heightOrig) = getimagesize($filename);
     
               if ( $heightOrig > 0 ) {
                    
                    $ratioOrig = $widthOrig/$heightOrig;
          
                    if ( ($width/$height) > $ratioOrig)
                         $width = $height * $ratioOrig;
                    else
                         $height = $width / $ratioOrig;
          
          
                    // Resample the original image
                    //
                    $image_p = imagecreatetruecolor($width, $height);
                    $image = imagecreatefromjpeg($filename);
                    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
          
          
                    // Output to a file and clear memory of the old images
                    //
                    imagejpeg($image_p, $newFilePath, $quality);
                    imagedestroy($image_p);
                    imagedestroy($image);
     
               } 

          } // if file_exists
     }


require_once('header.php');



?>

	

		<table border="0" cellspacing="0" cellpadding="0" width=100%>

		<tr>

		<td>

		<td>

		<IMG SRC="../Images/spacer.gif" width="10" height="10">

		</td>

		<td>

			<table border="0" cellspacing="0" cellpadding="0" width=100%>

			<tr>

			<td class="TitleText">

			<b>Photo List</b>

			</td>

			</tr>

			<tr>

			<td>&nbsp;<BR>

			</td>

			</tr>

			<tr>

			<td class="MainText">

			<P>

			Just sit back and watch the magical transformation happen!

			<P>

			<?php include ("help.php"); ?>

			</td>

			</tr>

			<tr>

			<td>

			&nbsp;<BR>

			</td>

			</tr>

			<tr>

			<td>

			<HR>

			</td>

			</tr>

			<tr>

			<td>&nbsp;<BR>

			</td>

			</tr>

			<tr>

			<td align="center">

				<table width=100% border="0">

				<tr>

				<td>

				<IMG SRC="../Images/spacer.gif" width="10" height="10">

				</td>

				<td align="center">

				

					<?php

					$width = 160;  // pixels
					$height = 100;   // pixels 
					$newFilePath = '../thumbs';
					$imageFolder = '../Photos';

					$querystate = "select * from photos order by photo_date";

					$resultstate = mysqli_query($cxn, $querystate)

					or die ("Couldn't execute query.");

					while ($query_row = mysqli_fetch_assoc($resultstate))
					{
					 $fileParts = pathinfo( $query_row['filepath'] );
					  $filename  = $fileParts['filename'];
					  $extension = strtolower( $fileParts['extension'] );
					  $origName  = "$imageFolder/$filename.$extension";
					  $newName   = "$newFilePath/$filename.$extension"; 
					  if ( $extension == "jpg" || $extension == "jpeg" ) {
						   jpgResizeFrom( $origName, $width, $height, $newName );
						   echo "<a href='./$origName'><img src='$newName' /></a>";
					  } 

						} 

					 ?>
					</table>&nbsp;<BR>

				

				</td>

				<td>

				<IMG SRC="../Images/spacer.gif" width="10" height="10">

				</td>

				</tr>

				</table>

			</td>

			</tr>

			</table>

		</td>

		

		<td>

		<IMG SRC="../Images/spacer.gif" width="10" height="10">

		</td>

		</tr>

		</table>

Open in new window

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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.

 
Beverley PortlockCommented:
The code is only processing files whose extensions are jpg and jpeg. Are the ones being skipped jpg files?
0
 
brucegustPHP DeveloperAuthor Commented:
Yes.
0
 
ramelongCommented:
If your code stops after a while, you may be expand the execution time of the server:
ini_set ( 'max_execution_time','15000' ); // in seconds

Open in new window

After the loop.
In order to help you with this: can you show the structure of the database table?
0
 
brucegustPHP DeveloperAuthor Commented:
Almost there!

The code works. I put in the error message dynamic at the front of the script and was able to determine that the image path wasn't rendering correctly. So I made that change and while I'm getting a nice, neat page of resized images, the new thumbnail isn't being put into my "thumbs" directory.

Why not? What am I missing? The new resized thumbnail needs to be stored in my "thumbs" folder, but nothing's being put in there.

We are poised on the threshold of greatness if I can just get that last little piece in place.

Thanks!
<?php



session_start(); 

if (@$_SESSION['auth'] != "yes")                   

{

header("Location: default.php");

exit();

}

ini_set('display_errors', 1);  error_reporting(E_ALL);


include ("../carter.inc");



$cxn = mysqli_connect($host,$user,$password,$database)

or die ("couldn't connect to server");

     function jpgResizeFrom( $filename, $width, $height, $newFilePath, $quality=75 ) { 
          if ( file_exists( $filename ) && !is_dir( $filename ) ) { 
               // Get current dimensions and calculate the best size
               list($widthOrig, $heightOrig) = getimagesize($filename);
     
               if ( $heightOrig > 0 ) {
                    
                    $ratioOrig = $widthOrig/$heightOrig;
          
                    if ( ($width/$height) > $ratioOrig)
                         $width = $height * $ratioOrig;
                    else
                         $height = $width / $ratioOrig;
          
          
                    // Resample the original image
                    //
                    $image_p = imagecreatetruecolor($width, $height);
                    $image = imagecreatefromjpeg($filename);
                    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
          
          
                    // Output to a file and clear memory of the old images
                    //
                    imagejpeg($image_p, $newFilePath, $quality);
                    imagedestroy($image_p);
                    imagedestroy($image);
     
               } 

          } // if file_exists
     }


require_once('header.php');



?>

	

		<table border="0" cellspacing="0" cellpadding="0" width=100%>

		<tr>

		<td>

		<td>

		<IMG SRC="../Images/spacer.gif" width="10" height="10">

		</td>

		<td>

			<table border="0" cellspacing="0" cellpadding="0" width=100%>

			<tr>

			<td class="TitleText">

			<b>Photo List</b>

			</td>

			</tr>

			<tr>

			<td>&nbsp;<BR>

			</td>

			</tr>

			<tr>

			<td class="MainText">

			<P>

			Just sit back and watch the magical transformation happen!

			<P>

			<?php include ("help.php"); ?>

			</td>

			</tr>

			<tr>

			<td>

			&nbsp;<BR>

			</td>

			</tr>

			<tr>

			<td>

			<HR>

			</td>

			</tr>

			<tr>

			<td>&nbsp;<BR>

			</td>

			</tr>

			<tr>

			<td align="center">

				<table width=100% border="0">

				<tr>

				<td>

				<IMG SRC="../Images/spacer.gif" width="10" height="10">

				</td>

				<td align="center">

				
					<table>
					<?php

					$width = 160;  // pixels
					$height = 100;   // pixels 
					$newFilePath = '../thumbs/';
					$imageFolder = '../Photos/';

					$querystate = "select * from photos order by photo_date";

					$resultstate = mysqli_query($cxn, $querystate)

					or die ("Couldn't execute query.");

					while ($query_row = mysqli_fetch_assoc($resultstate))
					{
					?>
					<tr>
					<td>
					<?php
					 $fileParts = pathinfo($query_row['url'] );
					  $filename  = $fileParts['filename'];
					  $extension = strtolower( $fileParts['extension'] );
					  $origName  = "$imageFolder/$filename.$extension";
					  $newName   = "$newFilePath/$filename.$extension"; 
					  if ( $extension == "jpg" || $extension == "jpeg" ) {
						   jpgResizeFrom( $origName, $width, $height, $newName );
						   echo "<a href='./$origName'><img src='$newName' /></a>";
					  } 

						} 

					 ?>
					 </td>
					 </tr>
					 </table>
				 </td>
				 </tr>
					</table>&nbsp;<BR>

				

				</td>

				<td>

				<IMG SRC="../Images/spacer.gif" width="10" height="10">

				</td>

				</tr>

				</table>

			</td>

			</tr>

			</table>

		</td>

		

		<td>

		<IMG SRC="../Images/spacer.gif" width="10" height="10">

		</td>

		</tr>

		</table>

Open in new window

0
 
Beverley PortlockCommented:
Check permissions on the thumbs folder. The webserver needs to be able to write the files in there. Keep it simple for now and set the permissions on that folder to 777 - it's only JPGs in there, not critical stuff.
0
 
brucegustPHP DeveloperAuthor Commented:
Nah, "thumbs" are set to 777 so we're good there.

Where in the code is it where the file is actually being moved to the "thumbs" directory?
0
 
ramelongCommented:
In
imagejpeg($image_p, $newFilePath, $quality);

Open in new window

$image_p have the path in it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.