Jump to content

[SOLVED] Generating thumbnails, writing path to mySQL database and displaying them.


webmaster1

Recommended Posts

Hi All,

 

I have a form that allows three image file uploads. I want to display (output into a browser from mySQL) the images in two different sizes (regular size and thumbnail size).

 

I was really hoping it would be as simple as:

 

<?php <img src=".$imageurl1." width = "whatever size I need it outputted as"> ?>

 

This doesn't work and apparently I have go through this complicated process that relies on a GD Library (which I have installed). I've set up three folders:

 

[*]upload/  - for images in the default size the user uploads

[*]upload/regular  - for images resized for outputting in site

[*]upload/thumbnail  - for images resized for outputting as thumbnails

 

Here's a skeletal example of the code I'm working with:

 



<?php
if (isset($_POST['submit']))

{
//LOTS OF OMITTED VALIDATION HERE

                  $path1= "upload/".$HTTP_POST_FILES['ufile']['name'][0];
                  $path2= "upload/".$HTTP_POST_FILES['ufile']['name'][1];
                  $path3= "upload/".$HTTP_POST_FILES['ufile']['name'][2];

                  copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);
                  copy($HTTP_POST_FILES['ufile']['tmp_name'][1], $path2);
                  copy($HTTP_POST_FILES['ufile']['tmp_name'][2], $path3);

                  include("dbinfo.php");
          mysql_connect(localhost,$username,$password);
          @mysql_select_db($database) or die( "Unable to establish a connection to the relevant database.");

$query = "INSERT INTO test VALUES ('','','','','','','','','','','','','','','',NOW(),'','$path1','$path2','$path3')";
mysql_query($query);

                  echo "The following image files have been uploaded:</br></br>
                  ";

                  echo "File Name :".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>";
                  //echo "File Size :".$HTTP_POST_FILES['ufile']['size'][0]." KB<BR/>";
                  echo "File Type :".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>";
                  //echo "<img src=\"$path1\" height=\"150\">";
                  echo "<P>";

                  echo "File Name :".$HTTP_POST_FILES['ufile']['name'][1]."<BR/>";
                  //echo "File Size :".$HTTP_POST_FILES['ufile']['size'][1]."<BR/>";
                  echo "File Type :".$HTTP_POST_FILES['ufile']['type'][1]."<BR/>";
                  //echo "<img src=\"$path2\" height=\"150\">";
                  echo "<P>";

                  echo "File Name :".$HTTP_POST_FILES['ufile']['name'][2]."<BR/>";
                  //echo "File Size :".$HTTP_POST_FILES['ufile']['size'][2]."<BR/>";
                  echo "File Type :".$HTTP_POST_FILES['ufile']['type'][2]."<BR/>";
                  //echo "<img src=\"$path3\" height=\"150\">";
                  exit();
}
}
?>

<HTML>
<BODY>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<fieldset>
<?php
<ol>
    <li>
    <label for "ufile[]">Image File 1:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/>
    </li>
    <li>
    <label for "ufile[]">Image File 2:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/>
    </li>
    <li>
    <label for "ufile[]">Image File 3:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/>
    </li>   
    <li>
    <input name="submit" type="submit">
    </li>
</ol>
</fieldset>
</form>
</BODY>
</HTML>

 

Here's an example of the thumbnail generation code I'm working with though I don't even know where to start to stitch the three of them together  :-[

 

<?php
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
  // open the directory
  $dir = opendir( $pathToImages );

  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {
      echo "Creating thumbnail for {$fname} <br />";

      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
    }
  }
  // close the directory
  closedir( $dir );
}
// call createThumb function and pass to it as parameters the path 
// to the directory that contains images, the path to the directory
// in which thumbnails will be placed and the thumbnail's width. 
// We are assuming that the path will be a relative path working 
// both in the filesystem, and through the web for links
createThumbs("upload/","uploadthumbnails/",100);
?>

 

<?php
function createGallery( $pathToImages, $pathToThumbs ) 
{
  echo "Creating gallery.html <br />";

  $output = "<html>";
  $output .= "<head><title>Thumbnails</title></head>";
  $output .= "<body>";
  $output .= "<table cellspacing=\"0\" cellpadding=\"2\" width=\"500\">";
  $output .= "<tr>";

  // open the directory
  $dir = opendir( $pathToThumbs );

  $counter = 0;
  // loop through the directory
  while (false !== ($fname = readdir($dir)))
  {
    // strip the . and .. entries out
    if ($fname != '.' && $fname != '..') 
    {
      $output .= "<td valign=\"middle\" align=\"center\"><a href=\"{$pathToImages}{$fname}\">";
      $output .= "<img src=\"{$pathToThumbs}{$fname}\" border=\"0\" />";
      $output .= "</a></td>";

      $counter += 1;
      if ( $counter % 4 == 0 ) { $output .= "</tr><tr>"; }
    }
  }
  // close the directory
  closedir( $dir );

  $output .= "</tr>";
  $output .= "</table>";
  $output .= "</body>";
  $output .= "</html>";

  // open the file
  $fhandle = fopen( "gallery.html", "w" );
  // write the contents of the $output variable to the file
  fwrite( $fhandle, $output ); 
  // close the file
  fclose( $fhandle );
}
// call createGallery function and pass to it as parameters the path 
// to the directory that contains images and the path to the directory
// in which thumbnails will be placed. We are assuming that 
// the path will be a relative path working 
// both in the filesystem, and through the web for links
createGallery("upload/","uploadthumbnails/");
?>

 

:o Do I really have to go through this malarchy just to resize an image?

 

Link to comment
Share on other sites

The most rudimentary tutorial example I've come across uses a function:

 

<?php 
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth)
{
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
$origWidth = imagesx($srcImg);
$origHeight = imagesy($srcImg);

$ratio = $origWidth / $thumbWidth;
$thumbHeight = $origHeight * $ratio;

$thumbImg = imagecreate($thumbWidth, $thumbHeight);
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, imagesx($thumbImg), imagesy($thumbImg));

imagejpeg($thumbImg, "$thumbDirectory/$imageName");
}

createThumbnail("img", "theFileName.jpg", "img/thumbs", 100); 
?>

 

Does anybody know how I would "trigger" this function? Would I use a button on a single page or can I call on it in my main input form where the images are uploaded?

 

I'd apreciate any help; even being pointed in the right direction. I'm confidant that if I know where to start that I can work it out.

Link to comment
Share on other sites

:-X No takers eh?

 

I geuss I can always have the client resize the images themselves and submit a thumbnail size along with the regular image.

 

I'm just concerned that I'm creating work for them that the site should technically be doing for them in the first place.  :(

Link to comment
Share on other sites

After the user uploads the file through the form, you need to save it to the server.  You can use move_uploaded_file on the posted var.  From there, you can use regular html img attributes on whatever path/name you used in the 2nd argument for move_uploaded_file (the destination).

 

edit: though you should know, making a thumbnail like this will not reduce the amount of data being sent to the client when it's displayed.  A 100kb picture will still be sent as a full 100kb picture to the client on page request, and their browser will simply render it smaller.  You would want to go ahead and use the GD library to make a permanently resized "thumbnail" version, to reduce the amount of data being sent to client when viewing thumbnails.

Link to comment
Share on other sites

Yep, I'm aware that its not kind to bandwidth and all that jazz.

 

I've gone through several GD thumbnails tutorials and even looked at phpThumb but none of them seem to be dumbing it down enough for me.

 

Lets say I want to avoid GD completley. Are you saying that this should work?

 

<?php <img src=".$imageurl1." width = "whatever size I need it outputted as"> ?>

 

edit: I end up with a parse error whenever I include the width attribute.

 

Parse error: syntax error, unexpected T_LNUMBER, expecting ','
Link to comment
Share on other sites

Okay well you also don't have your quotes right.

 

The parse error is gone so the page loads but now my image won't show (the usual red x in a box in the topleft of where the image should be).

 

Do I need to include the height attribute and will it need to be proportional?

 

That makes sense btw , I presume the misuse of the " was closing off the echo.

 

 

Link to comment
Share on other sites

As far as the image not showing...okay well if you've verified that the file is uploaded and stored on your server...are you saying that

 

<?php 
   echo "<img src='$imageurl1'>"; 
?>

 

works, but not, for instance

 

<?php 
   echo "<img src='$imageurl1' width = '100'>"; 
?>

 

does not?

 

well....not putting the height attribute is not conforming to the standards.  Depends on the browser and version as to how it decides to render it, I suppose.  Turns out that FF3.0.4 will render it proportionally if I echo an image with just a width attribute.  Can't say for sure what other versions or browsers will do.

 

Link to comment
Share on other sites

Yes. It all works fine until I add the width attribute. I'm using an up to date IE.

 

I tried adding the proportionate height to the resize but to no avail.

 

ORIGINAL IMAGE: 500w 375h

 

RESIZED IMAGE: 250w 188h

 

Here's my output code:

 

<?php
include("dbinfo.php");

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM test";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();

echo "<b><center>Database Output</center></b><br><br>";

$i=0;
while ($i < $num) {

$index=mysql_result($result,$i,"index");
$make=mysql_result($result,$i,"make");
$model=mysql_result($result,$i,"model");
$price=mysql_result($result,$i,"price");
$engine=mysql_result($result,$i,"engine");
$transmission=mysql_result($result,$i,"transmission");
$year=mysql_result($result,$i,"year");
$colour=mysql_result($result,$i,"colour");
$mileagem=mysql_result($result,$i,"mileagem");
$mileagekm=mysql_result($result,$i,"mileagekm");
$owners=mysql_result($result,$i,"owners");
$doors=mysql_result($result,$i,"doors");
$location=mysql_result($result,$i,"location");
$info=mysql_result($result,$i,"info");
$date=mysql_result($result,$i,"date");
$ipaddress=mysql_result($result,$i,"ipaddress");
$imageurl1=mysql_result($result,$i,"imageurl1");
$imageurl2=mysql_result($result,$i,"imageurl2");
$imageurl3=mysql_result($result,$i,"imageurl3");

echo "
$index</br>
$make</br>
$model</br>
$price</br>
$engine</br>
$transmission</br>
$year</br>
$colour</br>
$mileagem</br>
$mileagekm</br>
$owners</br>
$doors</br>
$location</br>
$info</br>
$date</br>
$ipaddress</br>
<img src='.$imageurl1.' width='250' height='188'> </br>
<img src='.$imageurl2.'></br>
<img src='.$imageurl3.'></br>
</br>
<hr>
</br>
     ";
$i++;
}
?>

 

 

 

 

Link to comment
Share on other sites

hmm how about for shits and grins you try removing the .'s around those vars.  src='imageurl1'

 

Excellent. Shits and grins all around. FYI it doesn't need to be proportionate either.

 

One more question: Do you think I'll get away with this method for the following two scenarios?

 

Thumbnail Page: Consists of 10-20 images up to 80 kilobytes in size each.

Detail Page: Consists of 3 images again up to 80 kilobytes in size each.

 

edit: forgot to say thank you!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.