Solved

How do I make this function work

Posted on 2011-03-17
10
204 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
Comment Utility
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
Comment Utility
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
Comment Utility
The code is only processing files whose extensions are jpg and jpeg. Are the ones being skipped jpg files?
0
 

Author Comment

by:brucegust
Comment Utility
Yes.
0
 
LVL 6

Expert Comment

by:ramelong
Comment Utility
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
In
imagejpeg($image_p, $newFilePath, $quality);

Open in new window

$image_p have the path in it.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now