Go Back  DVD Talk Forum > General Discussions > Tech Talk
Reload this Page >

I call upon the Tech Forum PHP Gods once again

Tech Talk Discuss PC Hardware, Software, Internet and Other Technology

I call upon the Tech Forum PHP Gods once again

Old 08-08-05, 02:54 PM
  #1  
Mod Emeritus
Thread Starter
 
Gallant Pig's Avatar
 
Join Date: Aug 1999
Posts: 15,325
Likes: 0
Received 0 Likes on 0 Posts
I call upon the Tech Forum PHP Gods once again

This one is really frustating me.

OK so what I want to do is have images resized on the fly to a certain size so they'll look good when outputted on my page.

Here's my PHP script for resizing the images:
PHP Code:
 
I have this saved in its own PHP page. When I load it up, it looks great and works great.

Now the tricky part is getting it to show up on a html page. The only way I can get it to show up is to do this:

PHP Code:
<img src="http://www.pricecastle.com/image.php"
Again this works fine.

However, I need to call this a multiple number of times within the same page on the fly by passing it variables. Basically it's outputting images for a product display page.

I've tried to take the above script, and slightly change it to this:
PHP Code:
$upfile '$imageurl'
And then change my display page to pass the correct image location to it, like this:

PHP Code:

<img src="http://www.pricecastle.com/image.php?"
But no go... So how the heck can I use that script and have it generate nicely resized images on the fly???
Old 08-08-05, 03:17 PM
  #2  
Banned
 
Join Date: Sep 1999
Location: Memphis, TN
Posts: 11,544
Likes: 0
Received 0 Likes on 0 Posts
Originally Posted by Gallant Pig
I've tried to take the above script, and slightly change it to this:
PHP Code:
$upfile '$imageurl'
And then change my display page to pass the correct image location to it, like this:

PHP Code:

<img src="http://www.pricecastle.com/image.php?"
But no go... So how the heck can I use that script and have it generate nicely resized images on the fly???
Try this for that second piece there:

PHP Code:

<img src="http://www.pricecastle.com/image.php?imageurl="
Note that this is probably extremely unsafe, and may leave your script vulnerable to hacking. I'm not familiar enough with PHP to tell you the right way to do it. Nevertheless, this should at least work, which is a start.

Last edited by Otto; 08-08-05 at 04:54 PM.
Old 08-08-05, 03:51 PM
  #3  
DVD Talk Hall of Fame
 
Join Date: Feb 2000
Location: on the mountain
Posts: 7,849
Likes: 0
Received 0 Likes on 0 Posts
one note, you don't need

this code will do the same thing:


i'm not quite sure about the rest of your question though. i don't understand what isn't working. I would suggest putting all your images in the same directory so you don't have to send the whole URL but just a filename. Also, have you thought about the resources you will be using to use GD to resize images on every page load?

Last edited by moorehed; 08-08-05 at 03:54 PM.
Old 08-08-05, 05:26 PM
  #4  
Mod Emeritus
Thread Starter
 
Gallant Pig's Avatar
 
Join Date: Aug 1999
Posts: 15,325
Likes: 0
Received 0 Likes on 0 Posts
Otto, yes that's the way I had it. Typo on my part putting it into this thread.

Moorehed: the HTML page trying to display the image isn't working.
Old 08-08-05, 05:30 PM
  #5  
Banned
 
Join Date: Sep 1999
Location: Memphis, TN
Posts: 11,544
Likes: 0
Received 0 Likes on 0 Posts
So what does the HTML that page produces actually look like?

Does just having this in an HTML page work?
PHP Code:
<img src="http://www.pricecastle.com/image.php?imageurl=http://www.yahoo.com/testing.jpg"

Last edited by Otto; 08-08-05 at 05:35 PM.
Old 08-09-05, 12:31 AM
  #6  
DVD Talk Legend
 
Join Date: Jun 2000
Location: NYC
Posts: 17,018
Likes: 0
Received 0 Likes on 0 Posts
A few quick points.

- You don't need to wrap right-hand variables in a statement in quotes, unless you're creating a string with other text or variables. $whatever = $whatever is fine.

- Variables do not resolve in single quotes. '$whatever' prints as the string $whatever.

- You must make assignments in querystrings. ?something=something&whatever=whatever

- Like Moorehed said, doing this on every page load is a really bad practice. Passing in full URLs (or, god forbid, paths) is generally never a good idea when deal with files, as it opens up a potential server vulnerability. You should store the images in a directory with a thumbnails (100x100) subdirectory so you are handling a defined set of files. It sounds like you're sort of new to this, so if you want to challenge yourself, create a web interface to upload images (but only images, determined by MIME type!) to the images folder and automatically create your thumbnail.
Old 08-09-05, 10:52 AM
  #7  
Mod Emeritus
Thread Starter
 
Gallant Pig's Avatar
 
Join Date: Aug 1999
Posts: 15,325
Likes: 0
Received 0 Likes on 0 Posts
- You don't need to wrap right-hand variables in a statement in quotes, unless you're creating a string with other text or variables. $whatever = $whatever is fine.
This fixed it! Thanks!

So I'm switching this over to image based not path based, but do I still not want to call this so much on each page? Why not, resource hog?

Thanks again!
Old 08-09-05, 12:20 PM
  #8  
DVD Talk Legend
 
Join Date: Jun 2000
Location: NYC
Posts: 17,018
Likes: 0
Received 0 Likes on 0 Posts
Originally Posted by Gallant Pig
This fixed it! Thanks!
No problem!

So I'm switching this over to image based not path based, but do I still not want to call this so much on each page? Why not, resource hog?
Yep. It's doing it once versus doing it hundreds or thousands of times. On a low-traffic site it won't make a huge difference on the server end, but it will definitely be slower than viewing an image directly.
Old 08-29-05, 11:14 PM
  #9  
Mod Emeritus
Thread Starter
 
Gallant Pig's Avatar
 
Join Date: Aug 1999
Posts: 15,325
Likes: 0
Received 0 Likes on 0 Posts
Bumping from the grave....

You guys are right about the image script. It really slows down the site which is a bummer.

So ideally I guess what I'd like to do is when someone initially creates a product, to just enter a URL to the image location, then have the program take the URL fwrite it to an image directory doing all the resizing and stuff before it creates the file, then finally storing the image name (will make it an incremental field) with the product table.

So what GD function am I looking at here? imagecreatefromjpeg then use fwrite? The image creation and storing to a directory is the only thing I'm not sure about, the other stuff should be easy.

Or am I on the wrong track altogether? Is there a better way to do this image upload thing? To me the ideal way would be to use ftp php functions but I don't have access to that.
Old 08-30-05, 12:11 AM
  #10  
Banned
 
Join Date: Sep 1999
Location: Memphis, TN
Posts: 11,544
Likes: 0
Received 0 Likes on 0 Posts
Well, there's several ways you can improve performance. The general idea is to write the output that you were previously sending directly to the brower into a file with a name based on the request info. That way, when your script starts, if the file exists already, it can just use that file instead, skipping the image generation stuff.

One thing to note is that files do get corrupted, so you want to put in a random type of variable that will cause the file to be regenerated and resaved if the luck of the draw tells it to. Maybe 1 in 20 or 1 in 40 or something like that.

What you will actually change is the ImageJpeg() call. The second, optional, parameter specifies a filename to write the image to. Note that the filename you specify must exist, it won't create it. So use fopen to create the file first, then fclose it, then use ImageJpeg to write the jpeg file.

Last edited by Otto; 08-30-05 at 12:18 AM.
Old 08-30-05, 12:28 PM
  #11  
DVD Talk Reviewer/ Admin
 
Adam Tyner's Avatar
 
Join Date: Sep 1999
Location: Greenville, South Cackalack
Posts: 21,868
Received 8 Likes on 5 Posts
Originally Posted by Gallant Pig
Or am I on the wrong track altogether? Is there a better way to do this image upload thing? To me the ideal way would be to use ftp php functions but I don't have access to that.
Nah, GD is the way to go. I'll send you some code.
Old 08-30-05, 01:20 PM
  #12  
DVD Talk Reviewer/ Admin
 
Adam Tyner's Avatar
 
Join Date: Sep 1999
Location: Greenville, South Cackalack
Posts: 21,868
Received 8 Likes on 5 Posts
Code:
<?php
        
  // Enter the maximum dimensions of your image below.
  // For example, if you wanted the image to be no wider than 350 pixels and no taller than 125 pixels,
  // use 350 for the width and 125 for the height.  Images aren't resized TO those dimensions;
  // they're resized to fit WITHIN those dimensions.
               
  $resize = array("Width"=>250,
                  "Height"=>250);
            
  // The local directory where the images are held.
  // To make this example simple, just use a subdirectory underneath the current path
         
  $baseDir = './images';
            
  // The format to output this graphic to  
           
  $outputFormat = "jpg";
   
            
  /* +--------------------------------------------------+
     | You don't need to edit anything below this point |
     +--------------------------------------------------+ */


  // The script will try to create these directories if they don't exist

  if (!(is_dir($baseDir)))
      @mkdir($baseDir, 0777);
  
  if (!(is_dir($baseDir . '/cache')))
      @mkdir($baseDir . '/cache', 0777);
      
  // This function will build an image URL based on the location of this script and a passed file
  
  function buildImageURL($string)
  {
      global $PHP_SELF;

      $urlParameters = split('/', $PHP_SELF);
      $urlParameters[(count($urlParameters) - 1)] = $string;
  
      return 'http://' . getenv("HTTP_HOST") . join('/', $urlParameters);
  }     
  
  // This is a function to convert images to a format GD can work with
  
  function convertImage($file, $errorDescription = '')
  {            
      $imageDetails = @getimagesize($file);
                  
      switch ($imageDetails["mime"])
      {
         case 'image/jpeg':
         case 'image/pjpeg':
            $image = imagecreatefromjpeg($file);
            break;
  
         case 'image/png':
            $image = imagecreatefrompng($file);
            break;
            
         case 'image/gif':
            $image = imagecreatefromgif($file);
            break;

         default:
            $GLOBALS["___m"] = "I don't recognize the file format or MIME type of the $errorDescription file.";
            return false;
      }
      
      return $image;
  }
      
  // This function will resize the graphic based on a set of entered parameters; too lazy to comment this old code of mine
  
  function resizeGraphic($attributes = false)
  {
      if ($attributes["imagePath"])
      {
         $image = convertImage($attributes["sourceImage"], 'large image');
      }
      else if ($attributes["image"])
      {
         $image = $attributes["image"];
      }
      else
      {
         $GLOBALS["___m"] = "I didn't get a valid image to resize.";
         return false;
      }        
      
      $randomString = md5(rand() . time());
      $basePath = $attributes["cacheDirectory"] . $randomString;
      $baseURL = $attributes["cacheURL"] . $randomString;
         
      $imageWidth = imagesx($image);
      $imageHeight = imagesy($image);
            
      $aspectRatio = $imageWidth / $imageHeight;
         
      $lengthiestWidth = ($aspectRatio * $attributes["height"]);
      $lengthiestHeight = ($attributes["width"] / $aspectRatio);
            
      if ($lengthiestWidth <= $attributes["width"])
          $attributes["width"] = $lengthiestWidth;
            
      if ($lengthiestHeight <= $attributes["height"])
          $attributes["height"] = $lengthiestHeight;
            
      $thumb = imagecreatetruecolor($attributes["width"], $attributes["height"]);
      imagecopyresampled($thumb, $image, 0, 0, 0, 0, $attributes["width"], $attributes["height"], $imageWidth, $imageHeight);
      
      if ($attributes["returnRawImage"])
      {
          return $thumb;
      }
      else
      {
          switch ($attributes["outputFormat"] = strtolower($attributes["outputFormat"]))
          {
               case 'jpg':
         
                  imagejpeg($thumb, $basePath . '-thumb.jpg');
      
                  break;
         
               case 'gif':
                  imagegif($thumb, $basePath . '-thumb.gif');
       
                  break;
         
               default:
      
                  $attributes["outputFormat"] = 'png';
      
                  imagepng($thumb, $basePath . '-thumb.png');
         
                  break;
          }
            
          $localFile = $basePath . '-thumb.' . $attributes["outputFormat"];
         
          $imageDetails = @getimagesize($localFile);
      
          $image = array("URL"=>$baseURL . '-image.' . $attributes["outputFormat"],
                         "Path"=>$localFile,
                         "Width"=>$imageDetails[0],
                         "Height"=>$imageDetails[1],
                         "MIME"=>$imageDetails["mime"]);
          
          return $image;
      }
  }
      
  // Looks for "___p", which I use as a "process" flag
       
  switch ($___p)
  {
      case FALSE:
       
        // The form has not been submitted; do nothing
           
        break;
         
      default:
      
       // The form has been submitted, so process as necessary
         
        if (strlen($attachment))
        {
           $imageDetails = @getimagesize($attachment);
                  
           unset($extension);
               
           if (ereg("jpeg", $imageDetails["mime"]))
              $extension = 'jpg';
           else if (ereg("gif", $imageDetails["mime"]))
              $extension = 'gif';
           else if (ereg("png", $imageDetails["mime"]))
              $extension = 'png';
           else
           {
              // "___m" is my way of passing error messages to the user
         
              $___m = "I don't recognize this file type.  Please upload a PNG, JPEG, or GIF.";
              break;
           }
                         
           // If it looks like a valid image has been uploaded, resize
                         
           if (is_uploaded_file($attachment) &&
               is_numeric($imageDetails[0]) && $imageDetails[0] != 0 &&
               is_numeric($imageDetails[1]) && $imageDetails[1] != 0)
           {
               // I'm just assigning a timestamp as the filename to give it some randomness
      
               $destination = $baseDir . '/' . time() . '.' . $extension;
       
               // Move the uploaded file to the destination
               move_uploaded_file($attachment, $destination);
      
               // Resize the graphic
               $attributes = array("imagePath"=>$destination,
                                   "sourceImage"=>$destination,
                                   "cacheDirectory"=>"$baseDir/cache/",
                                   "outputFormat"=>$outputFormat,
                                   "width"=>$resize["Width"],
                                   "height"=>$resize["Height"]);
       
               $resizedImage = resizeGraphic($attributes);
        
               // Move some files around and clean up
               @copy($resizedImage["Path"], $destination);
               @chmod($destination, 0644);
               @unlink($resizedImage["Path"]);
               
               // Again, working under the assumption that your image directory is underneath the current dir...
               $imageURL = str_replace('./', '', $destination);
           }
        }
        else
        {
           // The user didn't select a file
            
           $___m = "Please select a file.";
           break;
        }
  }
            
?>                       
<html>
<head>                   
<title>Image Upload/Resize Test For Gallant Pig</title>
</head>
<body>
            
<?php
      
  // print any error messages to the user
       
  if (strlen($___m))
      print '<div align="center" style="color: #cc0000; font-weight: bold">' . $___m . '</div>' . "\n";
      
?>
               
<div align="center">
<form method="POST" action="<?= $PHP_SELF ?>" enctype="multipart/form-data">
<table cellpadding="3" cellspacing="0" border="0">
                                   
<?php
       
  if (strlen($imageURL))
  {     
      $imageDetails = @getimagesize($imageURL);
               
      print '<tr>' . "\n" .
            '<td class="sz2" align="center" colspan="2">' . "\n" .
            '<img src="' . $imageURL .
            '?rand=' . rand() . '" border="1" ' . $imageDetails[3] . '></td>' . "\n" .
            '</tr>' . "\n" .
            '<tr>' . "\n" .
            '<td class="sz2" align="center" colspan="2">' . "\n" .
            buildImageURL($imageURL) .
            '</td>' . "\n" .
            '</tr>' . "\n";
            
  }
           
?>
   
<tr>        
<td class="sz2" nowrap align="right">
Browse for the file you'd like to upload for the photo on the front page:<br>
<small>(this picture will be resized to fit in a <?= $resize["Width"] ?>x<?= $resize["Height"] ?> window)</small>
</td>
<td class="sz2" valign="top">
<input name="attachment" type="file" class="button"></td>
</tr>       

<tr>  
<td rowspan="2" colspan="3" valign="middle" align="right">
<input type="submit" name="___a" width="47" height="45" alt="" border="0"
 tabindex="120" value="Set Image" class="button"></td>
</tr>
      
</table>
<input type="hidden" name="___p" value="1">
</form>
</div>

</body>                            
</html>
Old 08-30-05, 10:51 PM
  #13  
DVD Talk Legend
 
Join Date: Jun 2000
Location: NYC
Posts: 17,018
Likes: 0
Received 0 Likes on 0 Posts
Tables where divs would work -- noooooo!

Incidentally, ImageMagick is actually much better than GDlib -- faster, more accurate resizing, and still free. But GDlib will work well for your purposes, since PHP doesn't have any IM functions (yet?).

Adam's code does a good job if you want to upload the image. If you want to have the option to either upload or specify a URL, that's an easy modification... if the fopen URL wrappers are installed, you can just use fopen. Otherwise, look into fsockopen.

Last edited by Breakfast with Girls; 08-30-05 at 10:54 PM.
Old 08-31-05, 12:23 AM
  #14  
Mod Emeritus
Thread Starter
 
Gallant Pig's Avatar
 
Join Date: Aug 1999
Posts: 15,325
Likes: 0
Received 0 Likes on 0 Posts
Adam:

Matthew:

Otto:

THANKS GUYS!

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On
Trackbacks are Off
Pingbacks are Off
Refbacks are Off


Thread Tools
Search this Thread

Archive - Advertising - Cookie Policy - Privacy Statement - Terms of Service - Do Not Sell My Personal Information

Copyright 2018 MH Sub I, LLC dba Internet Brands. All rights reserved. Use of this site indicates your consent to the Terms of Use.