Solved

How do I make this function work

Posted on 2011-03-17
10
212 Views
Last Modified: 2012-05-11
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

0
Comment
Question by:brucegust
  • 4
  • 4
  • 2
10 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35160703
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
 

Author Comment

by:brucegust
ID: 35161070
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
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35161100
The code is only processing files whose extensions are jpg and jpeg. Are the ones being skipped jpg files?
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

 

Author Comment

by:brucegust
ID: 35161953
Yes.
0
 
LVL 6

Expert Comment

by:ramelong
ID: 35162545
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
 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 500 total points
ID: 35163800
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
 

Author Comment

by:brucegust
ID: 35165110
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
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35165241
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
 

Author Comment

by:brucegust
ID: 35165362
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
 
LVL 6

Expert Comment

by:ramelong
ID: 35165829
In
imagejpeg($image_p, $newFilePath, $quality);

Open in new window

$image_p have the path in it.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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…

808 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