?
Solved

How do I make this function work

Posted on 2011-03-17
10
Medium Priority
?
224 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

 

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 2000 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

Are You Using the Best Web Development Editor?

The worlds of web hosting and web development are constantly evolving. Every year we see design trends change, coding standards adapt and new frameworks/CMS created. With such a quick pace of change it’s easy to get lost trying to keep up.

See if your editor made the list.

Question has a verified solution.

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

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
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…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

770 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