Solved

Upload image with auto thumbnail created?

Posted on 2004-08-10
39
330 Views
Last Modified: 2012-05-05
Hi All,

I have been reading through the site about different thumbnail creation with GD or ImageMagick. I don't mind which I use, but I think I'd prefer support for both JPEG's and GIF's, which rules GD out.

I can upload an image and I can upload an resize an image, but I just can't seem to upload 1 image and keep the original size and make a thumb of it. Is there anybody who can help me?

I am not sure whether or not to have the original images and the thumbs in the same dir or not, but that doesn't bother me at all... All I need is a name to store in the db to which I can add a tn_ (or similar) to when calling for the thumbnail.

Any help is muchly appreciated.

Christian
0
Comment
Question by:theprankstanator
  • 16
  • 13
  • 10
39 Comments
 
LVL 25

Assisted Solution

by:Squinky
Squinky earned 350 total points
Comment Utility
It doesn't rule out GD - it can read GIFs, just not write them, so create JPEG or PNG previews for your GIF files. GD will regain GIF creation in PHP 5.0.1 now that the LZW patent has lapsed.

I usually keep thumbs and images in separate folders so that you don't have to change filenames (though you'd have to cope with different names if you change format for thumbnails).

The trick in creating your thumbnails is to grab your source image, make the thumbnail and save it to a separate file: I've adapted this from a function I've used before:

$psize is the size of the square that you want the preview to fit within (it's a square as it copes with portrait and landscape and preserves aspect ratio).
$sourcefile is the path to the original file
$pdestfile is the path to where you want the preview to be saved
$g_imgcomp is teh comression amount

function resampimagejpg($psize, $sourcefile, $pdestfile, $g_imgcomp) {
      $g_srcfile=$sourcefile;
      
      if(file_exists($sourcefile)) {
            //Get data from source image
            $g_is=getimagesize($sourcefile);
            $img_src=imagecreatefromjpeg($sourcefile);
            //Create preview sized image
            if ($g_is[0] > $psize or $g_is[1] > $psize) { //Only shrink, don't enlarge to fit
                  $g_fw=$psize;
                  $g_fh=$psize;
                  if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh)) {
                        $g_iw=$g_fw;
                        $g_ih=($g_fw/$g_is[0])*$g_is[1];
                  } else {
                        $g_ih=$g_fh;
                        $g_iw=($g_ih/$g_is[1])*$g_is[0];
                  }
                  $img_dst=imagecreatetruecolor($g_iw,$g_ih);
                  imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
            } else { //Just copy the image
                  $img_dst = $img_src;
            }
            imageinterlace($img_dst, 1);
            imagejpeg($img_dst, $pdestfile, $g_imgcomp);
            imagedestroy($img_dst);
            return true;
      } else {
            return false;
      }
}
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
oops, that example only reads JPEGs! you need to add something like this:

function resampimagejpg($psize, $isize, $sourcefile, $pdestfile, $g_imgcomp) {
      $g_srcfile=$sourcefile;
      
      if(file_exists($sourcefile)) {
            //Get data from source image
            $g_is=getimagesize($sourcefile);
            $p = pathinfo($sourcefile);
            switch ($p['extension']) {
                  case 'gif':
                        $img_src=imagecreatefromjpeg($sourcefile);
                        break;
                  case 'jpg':
                  case 'jpeg':
                        $img_src=imagecreatefromgif($sourcefile);
                        break;
                  case 'png':
                        $img_src=imagecreatefrompng($sourcefile);
                        break;
                  default:
                        return false; //Can't handle other formats
            }
            //Create preview sized image
            if ($g_is[0] > $psize or $g_is[1] > $psize) { //Only shrink, don't enlarge to fit
                  $g_fw=$psize;
                  $g_fh=$psize;
                  if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh)) {
                        $g_iw=$g_fw;
                        $g_ih=($g_fw/$g_is[0])*$g_is[1];
                  } else {
                        $g_ih=$g_fh;
                        $g_iw=($g_ih/$g_is[1])*$g_is[0];
                  }
                  $img_dst=imagecreatetruecolor($g_iw,$g_ih);
                  imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
            } else { //Just copy the image
                  $img_dst = $img_src;
            }
            imageinterlace($img_dst, 1);
            imagejpeg($img_dst, $pdestfile, $g_imgcomp);
            imagedestroy($img_dst);
            return true;
      } else {
            return false;
      }
}

And looking at the docs for http://www.php.net/manual/en/function.imagecreatefromgif.php, it does seem that the removal of GIF support also included reading. duh. Fortunately that page also lists some nice workarounds (including a native PHP GIF reader!).
0
 

Author Comment

by:theprankstanator
Comment Utility
Squinky - Fantastic, let me give it a shot and I'll report back shortly.

Thanks.
0
 

Author Comment

by:theprankstanator
Comment Utility
Sorry - Just need to clarify this.
After I upload an Image, do I then run this code for the OUTPUT, or do I use this to resize the image and THEN move to the directory?

Does that make sense?
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
You can use this function to do both at once as you can specify different paths for source and destination. So you could give it a file in '/tmp/uploadedimage.jpg' and tell it to save the thumbnail in '/var/www/html/mypics/thumbs/uploadedimage.jpg'. You still need to move the source file separately to wherever you want it; you can do that before or after creating the thumbnail, as long as you keep the input path pointed at the right file.
0
 

Author Comment

by:theprankstanator
Comment Utility
Hi Squinky,

I am having a hard time understanding what you mean. The user would be uploading an image from a form. I dont see how I could incorporate the source file directory in that way with a form.

Thanks,

Christian
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Once an image is uploaded, you need to call http://www.php.net/manual/en/function.move-uploaded-file.php to put the file where you want it and rename it to something sensible (like its original name) as it will have a temporary name after upload. Then you have a file that you can pass to that function. It's up to your script where the file is moved to (not the form).
0
 

Author Comment

by:theprankstanator
Comment Utility
But, at what stage would I run your script?
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Whenever you want to! At a guess, in the same script that you use to handle the upload form:

<?php
      $uploaddir = '/var/www/uploads/';
      $uploadfile = $uploaddir . $_FILES['userfile']['name'];
      $thumbnaildir = '/var/www/uploads/thumbs/';
      
      if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
            resampimagejpg(128, $uploadfile, $thumbnaildir.$_FILES['userfile']['name'], 75);
      }
?>

Obviously, set the directories where you want your files to really live.

(delete the $isize param from my last version of the function it should not be there!)
0
 

Author Comment

by:theprankstanator
Comment Utility
I am getting a lot of undefined index errors on $_FILES['image']['name']
Also a cannot modify header error too...

This is what I have added of yours;

*************************************
$psize = "200";
$sourcefile = $_FILES['image']['tmp_name'];
$pdestfile = "/home/web/Client - Powerplay/images/parts/";
$g_imgcomp  = "50";


function resampimagejpg($psize, $sourcefile, $pdestfile, $g_imgcomp) {
     $g_srcfile=$sourcefile;
     
     if(file_exists($sourcefile)) {
          //Get data from source image
          $g_is=getimagesize($sourcefile);
          $p = pathinfo($sourcefile);
          switch ($p['extension']) {
               case 'gif':
                    $img_src=imagecreatefromjpeg($sourcefile);
                    break;
               case 'jpg':
               case 'jpeg':
                    $img_src=imagecreatefromgif($sourcefile);
                    break;
               case 'png':
                    $img_src=imagecreatefrompng($sourcefile);
                    break;
               default:
                    return false; //Can't handle other formats
          }
          //Create preview sized image
          if ($g_is[0] > $psize or $g_is[1] > $psize) { //Only shrink, don't enlarge to fit
               $g_fw=$psize;
               $g_fh=$psize;
               if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh)) {
                    $g_iw=$g_fw;
                    $g_ih=($g_fw/$g_is[0])*$g_is[1];
               } else {
                    $g_ih=$g_fh;
                    $g_iw=($g_ih/$g_is[1])*$g_is[0];
               }
               $img_dst=imagecreatetruecolor($g_iw,$g_ih);
               imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
          } else { //Just copy the image
               $img_dst = $img_src;
          }
          imageinterlace($img_dst, 1);
          imagejpeg($img_dst, $pdestfile, $g_imgcomp);
          imagedestroy($img_dst);
          return true;
     } else {
          return false;
     }
}

$uploaddir = '/home/web/Client - Powerplay/images/parts/';
$uploadfile = $uploaddir . $_FILES['image']['name'];
$thumbnaildir = '/home/web/Client - Powerplay/images/parts/thumbs/';
     
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
resampimagejpg(128, $uploadfile, $thumbnaildir.$_FILES['image']['name'], 75);
}
*************************************
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Your path has unescaped, unquoted spaces in which could well cause problems. Try a path with no spaces, and if that works, deal with the quoting.

The headers errors are cause by the first error, so they'll go away when you fix the first error.

That article is quite good, but you end up with much the same code.
0
 

Author Comment

by:theprankstanator
Comment Utility
Hi Squinky - still no luck, my code is now this;

*********************************************
$psize = "200";
$sourcefile = $_FILES['image']['tmp_name'];
$pdestfile = "/home/web/Powerplay/images/parts/";
$g_imgcomp  = "50";


function resampimagejpg($psize, $sourcefile, $pdestfile, $g_imgcomp) {
     $g_srcfile=$sourcefile;
     
     if(file_exists($sourcefile)) {
          //Get data from source image
          $g_is=getimagesize($sourcefile);
          $p = pathinfo($sourcefile);
          switch ($p['extension']) {
               case 'gif':
                    $img_src=imagecreatefromjpeg($sourcefile);
                    break;
               case 'jpg':
               case 'jpeg':
                    $img_src=imagecreatefromgif($sourcefile);
                    break;
               case 'png':
                    $img_src=imagecreatefrompng($sourcefile);
                    break;
               default:
                    return false; //Can't handle other formats
          }
          //Create preview sized image
          if ($g_is[0] > $psize or $g_is[1] > $psize) { //Only shrink, don't enlarge to fit
               $g_fw=$psize;
               $g_fh=$psize;
               if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh)) {
                    $g_iw=$g_fw;
                    $g_ih=($g_fw/$g_is[0])*$g_is[1];
               } else {
                    $g_ih=$g_fh;
                    $g_iw=($g_ih/$g_is[1])*$g_is[0];
               }
               $img_dst=imagecreatetruecolor($g_iw,$g_ih);
               imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
          } else { //Just copy the image
               $img_dst = $img_src;
          }
          imageinterlace($img_dst, 1);
          imagejpeg($img_dst, $pdestfile, $g_imgcomp);
          imagedestroy($img_dst);
          return true;
     } else {
          return false;
     }
}

$uploaddir = '/home/web/Powerplay/images/parts/';
$uploadfile = $uploaddir . $_FILES['image']['name'];
$thumbnaildir = '/home/web/Powerplay/images/parts/thumbs/';
     
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
resampimagejpg(128, $uploadfile, $thumbnaildir.$_FILES['image']['name'], 75);
}
****************************************

Gives me the following errors when I submit the form;
****************************************
Notice: Undefined index: image in /home/web/PowerPlay/admin/add_recycle.php on line 33

Notice: Undefined index: image in /home/web/PowerPlay/admin/add_recycle.php on line 85

Notice: Undefined index: image in /home/web/PowerPlay/admin/add_recycle.php on line 88

Notice: Undefined index: image in /home/web/PowerPlay/admin/add_recycle.php on line 97

Warning: Cannot modify header information - headers already sent by (output started at /home/web/PowerPlay/admin/admin_header.php:7) in /home/web/PowerPlay/admin/add_recycle.php on line 108
****************************************

And I dont get any images uploaded. (or sideloaded :) its just on a test server atm)

Christian
0
 

Author Comment

by:theprankstanator
Comment Utility
Hello?

Can anybody help me with this?

Thanks
0
 
LVL 4

Accepted Solution

by:
kolpdc earned 150 total points
Comment Utility
i took a very short look at it, but it is not done with a very short look.

i can only recommend you what i did above: http://www.onlinetools.org/articles/creating_thumbnails_all.php - they provide all informations required to get your job done. from getting gd over integrating into php and apache till a complete testexample. just give it a short look before you continue with your problem. perhaps it is solved quicklier.

with the link i mentioned above, i solved the same problem like yours in around four hours (i had to integrate it into a bigger environment - so less time is needed).

do not look for gd, but gd2 and eventually special gif-mod. it works with jpg, png and gif - no problem.
0
 

Author Comment

by:theprankstanator
Comment Utility
Hi kolpdc,

I have played around and got it to work, but the only problem is that the thumbnails it creates are just black. Any ideas?

Christian
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Apologies for not getting back sooner.

This error:

Notice: Undefined index: image in /home/web/PowerPlay/admin/add_recycle.php on line 33

suggests that your form is not built correctly. It's saying that your uploaded file has no name, which suggests that it has not actually been uploaded at all. I notice that neither your script nor the one at onlinetools is checking that an uplaod actually happened, which would explain blank thumbnails too - you should add lines testing:

if (count($_FILES) > 0 and array_key_exists('image', $_FILES)) {
  if (is_uploaded_file($_FILES['image']['tmp_name'])) {
...

before trying to use the file.

To make sure that files are being uploaded, make sure you set a <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> in the form, and that you've set upload_max_filesize to a sensible value in php.ini
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
what kind of images do you create? i currently work with jpeg. does it well.

which gd-version do you use? did you forget to activate a module?



does not belong to your question, but i just remember, i changed the dimensioning.
       //Get dimensions and calculate thumbdimensions
       //y(th) = x(th) / x(old) * y(old)
       $old_x   = imageSX($src_img);
       $old_y   = imageSY($src_img);
       $thumb_w = 200;
       $thumb_h = $thumb_w / $old_x * $old_y;
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Having a fixed width will mean that portrait images will be much bigger than landscape ones. This is why I specify a square that thumbnails are fitted into, rather than fixing one dimension.
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
i used 200 because i need to have all images a width of 200 no matter of height. what i wanted to say was, i'd not absolutely recommend using the dimensioning provided by the script. the formula y(new) = x(new) / x(old) * y(old) provides all you need. so eventually forget about that big if-cascade and use mathematics. but it's nothing of importance.
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
like mentioned, i only use jpg at the moment. my first (working) function looks like following:

    //Create a thumbnail from a given picturefile
    function createThumb(
                        $path,            //The path of the graphicsfolder
                        $filename)      //The name of the sourcefile
    {
       global $gd2;

       //Check for jpeg-extension and create picture-object
       $system = explode(".", $filename);
       if (preg_match("/jpg|jpeg/", $system[1])) {
          $src_img = imagecreatefromjpeg($path.$filename);
       }

       //Create name of thumb   --- just separates my filename from path and add th_...
       $filename_th = getThumbName($filename);

       //Get dimensions and calculate thumbdimensions
       //y(th) = x(th) / x(old) * y(old)
       $old_x   = imageSX($src_img);
       $old_y   = imageSY($src_img);
       $thumb_w = 200;
       $thumb_h = $thumb_w / $old_x * $old_y;

       //Create the thumb-image as 256 or truecolor
       if ($gd2=="") {
          $dst_img = ImageCreate($thumb_w, $thumb_h);
          imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
       }
       else {
          $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
          imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x,$old_y);
       }

       //Create the thumb and save it to server
       imagejpeg($dst_img, $path.$filename_th);
 
       //Free memory
       imagedestroy($dst_img);
       imagedestroy($src_img);

       return $filename_th;
    } //createThumb
0
 

Author Comment

by:theprankstanator
Comment Utility
Squinky - I fixed my form (the issue is too embarresing to mention on here) and the script now just returns;
 
Fatal error: Call to undefined function: imagecreatefromjpeg() in d:\web\htdocs\powerplay\site\admin\add_recycle.php on line 64
 
There was an error in the switch, where the gif was called imagecreatefromjpeg (and vice versa) and i fixed it, but am still getting that error (which refers to the imagecreatefromjpeg line in the switch).

Kolpdc - I have tried it on 2 machines now and the images are just black. :(
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
-what kind of graphic-format? gif? jpg? png? please choose an examplefile and tell me type, name, graphical-settings (size, colors)
-what is your infrastructure? do you have your own server (where you are allowed to change settings?) or do you depend on a providers server with pre-configured settings?
-did you take a look - are the created thumbs physically created on your server (do the files have a reasonable physical size?)
-has the directory where you like to create your thumbs into the right accessrights?
-perhaps one of your dlls required for gd have an error inside?

-should not take you too long - try the function i provided above if it seems reasonable to you.
    - change following part the way, that your $thumbfilename = "th_".$filename;
      just to try. use a jpeg-file. hope you have gd2 activated? (not gd.dll, but gd2.dll)

       //Create name of thumb   --- just separates my filename from path and add th_...
       $filename_th = getThumbName($filename);
    - just leave $thumb_w = 200 - it's only to test. later you could modify it.
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Fatal error: Call to undefined function: imagecreatefromjpeg() in d:\web\htdocs\powerplay\site\admin\add_recycle.php on line 64

That does sound like you don't have GD2 in your PHP setup. Make sure by doing a phpinfo() and looking for GD in the output, which should contain --with-gd in the configure line, and something like this in the modules section:

gd

GD Support => enabled
GD Version => bundled (2.0.28 compatible)
FreeType Support => enabled
FreeType Linkage => with freetype
FreeType Version => 2.1.4
GIF Read Support => enabled
GIF Create Support => enabled
JPG Support => enabled
PNG Support => enabled
WBMP Support => enabled
XBM Support => enabled

This is from my PHP 5.0.1 installation - you can see that it has GIF creation as standard now.
0
 

Author Comment

by:theprankstanator
Comment Utility
Squinky, all fixed now.
I can upload the images and they resize and save in the right dir, but 2 quick questions - How do I keep the original image in one directory? (atm, it is only giving me one copy of the image as the thumbnail in its dir). and 2nd question, How do I rename the thumb? I have tried
$uploaddir = '../images/parts';
$filename = "1_" . date("d_m_Y_H_i") . "_" . $_FILES['image']['name'];
$uploadfile = $uploaddir . $filename;
$thumbnaildir = '../images/parts/thumbs/';
but to no avail.

Thanks.

kolpdc, lemme just try this one of squinkys again before i try yours again. Thanks! :)
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
i think squinky is right. seems you have gd enabled - not gd2.

in your php.ini change the following:

extension=php_gd.dll
;extension=php_gd2.dll

    v  v  v  v

;extension=php_gd.dll
extension=php_gd2.dll

then phpinfo() should return something like this in the gd-section: GD Version - 2.0 (or higher)
0
 

Author Comment

by:theprankstanator
Comment Utility
Yeah, I have sorted that now on my local machine (then I have a linux test box which I have not sorted and my linux live box which is constantly up to date with PHP, Apache, GD etc)
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
As I said earlier, you need to use move_uploaded_file() to put your original image where you want it. It's safest to do this, then create the thumbnail using the path to the original file's new location.

To set the name of the resulting thumbnail, just set the $pdestfile parameter to the full path, including the filename:

$pdestfile = $thumbnaildir.$filename;

then:

resampimagejpg(128, $uploadfile, $pdestfile, 75);
0
 

Author Comment

by:theprankstanator
Comment Utility
This is what I have now - I am just getting confused with setting the paths in 2 places....

***************************************
if ($_FILES["image"]["name"] != "")
{
  $pic_name = "1_" . date("d_m_Y_H_i") . "_" . $_FILES['image']['name'];
} else {
  $pic_name = "";
}
move_uploaded_file($_FILES['image']['tmp_name'], "../images/parts/{$pic_name}");

$psize = "200";
$sourcefile = "../images/parts/{$pic_name}";
$pdestfile = "../images/parts/thumbs/tn_{$pic_name}";
$g_imgcomp  = "50";


function resampimagejpg($psize, $sourcefile, $pdestfile, $g_imgcomp) {
     $g_srcfile=$sourcefile;
     
     if(file_exists($sourcefile)) {
          //Get data from source image
          $g_is=getimagesize($sourcefile);
          $p = pathinfo($sourcefile);
          switch ($p['extension']) {
               case 'gif':
                    $img_src=imagecreatefromgif($sourcefile);
                    break;
               case 'jpg':
               case 'jpeg':
                    $img_src=imagecreatefromjpeg($sourcefile);
                    break;
               case 'png':
                    $img_src=imagecreatefrompng($sourcefile);
                    break;
               default:
                    return false; //Can't handle other formats
          }
          //Create preview sized image
          if ($g_is[0] > $psize or $g_is[1] > $psize) { //Only shrink, don't enlarge to fit
               $g_fw=$psize;
               $g_fh=$psize;
               if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh)) {
                    $g_iw=$g_fw;
                    $g_ih=($g_fw/$g_is[0])*$g_is[1];
               } else {
                    $g_ih=$g_fh;
                    $g_iw=($g_ih/$g_is[1])*$g_is[0];
               }
               $img_dst=imagecreatetruecolor($g_iw,$g_ih);
               imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
          } else { //Just copy the image
               $img_dst = $img_src;
          }
          imageinterlace($img_dst, 1);
          imagejpeg($img_dst, $pdestfile, $g_imgcomp);
          imagedestroy($img_dst);
          return true;
     } else {
          return false;
     }
}

$uploaddir = '../images/parts';
$filename = "1_" . date("d_m_Y_H_i") . "_" . $_FILES['image']['name'];
$uploadfile = $pdestfile;
$thumbnaildir = '../images/parts/thumbs/';
     
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
resampimagejpg(128, $uploadfile, $pdestfile, 75);
}
**********************************************
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
i just took a short look (perhaps too short;).

i would change your problem a little and disconnect the problems from each other - so the overview gets better. i'd use three parts
1.) my variables and definitions. (paths, ...) at last functioncall.
2.) function for problem copy uploaded image to new directory (we already know both directories - see above;).
3.) function for resizing the image using gd2.

if it is confusing using two paths, just only use one directory and at a prefix to your filename. then there is nothing confusing. try following function to achieve the aim of adding a prefix "th_" to a file that also could have a pathinformation.

********************************

    //Create name of thumbnail from filename
    function getThumbName(
                        $filename)
    {
        if (strpos($filename, "\\") > 0)
            $filename_th = "th_".substr(strrchr($filename, "\\"), 1);
        else
            $filename_th = "th_".$filename;

        return $filename_th;
    } //getThumbname

    //Create name of thumb   --- just separates my filename from path and add th_...
    $filename_th = getThumbName($filename);

********************************
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Yes, that is looking a bit confused!

Keep the function as it is, and use this for the rest of your code:

//Check that there was actually an upload before proceeding
if (count($_FILES) > 0 and array_key_exists('image', $_FILES)) {
      if (is_uploaded_file($_FILES['image']['tmp_name'])) {
            if ($_FILES['image']['name'] != '')
            {
                  $pic_name = '1_' . date('d_m_Y_H_i') . '_' . $_FILES['image']['name'];
            } else {
                  exit; //Can't really do anything if we don't have a filename
            }
            $uploaddir = '../images/parts/';
            $thumbnaildir = '../images/parts/thumbs/';
            $sourcefile = $upload_dir.$pic_name;
            move_uploaded_file($_FILES['image']['tmp_name'], $sourcefile);
            $pdestfile = "{$thumbnail_dir}tn_{$pic_name}";

            $g_imgcomp = 50;
            $psize = 200;
            resampimagejpg($psize, $sourcefile, $pdestfile, $g_imgcomp);
      }
}

It could probably use some better error trapping, but it should work now!
0
 

Author Comment

by:theprankstanator
Comment Utility
I tried locally and on my live server, just got this error;
Fatal error: Call to undefined function: resampimagejpg() in /home/powerpla/public_html/admin/add_recycle.php on line 62
0
 

Author Comment

by:theprankstanator
Comment Utility
oh, to add to that, the original is there, just not the thumb.
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
ok - last try:

assuming you have
1.) gd better gd2 installed and running
2.) your image uploaded ($filename)
3.) and know into which ($path)
you may try the following - easy - code that works without problems:

(it will scale your thumbs to width 200 - but that's not your problem now)

good luck.

****************************

    //Create a thumbnail from a given picturefile
    function createThumb(
                        $path,            //The path of the graphicsfolder
                        $filename)      //The name of the sourcefile
    {
       global $gd2;

       //Check for jpeg-extension and create picture-object
       $system = explode(".", $filename);
       if (preg_match("/jpg|jpeg/", $system[1])) {
          $src_img = imagecreatefromjpeg($path.$filename);
       }

       //Create name of thumb
       $filename_th = getThumbName($filename);

       //Get dimensions and calculate thumbdimensions
       //y(th) = x(th) / x(old) * y(old)
       $old_x   = imageSX($src_img);
       $old_y   = imageSY($src_img);
       $thumb_w = 200;
       $thumb_h = $thumb_w / $old_x * $old_y;

       //Create the thumb-image as 256 or truecolor
       if ($gd2=="") {
          $dst_img = ImageCreate($thumb_w, $thumb_h);
          imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
       }
       else {
          $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
          imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x,$old_y);
       }

       //Create the thumb and save it to server
       imagejpeg($dst_img, $path.$filename_th);
 
       //Free memory
       imagedestroy($dst_img);
       imagedestroy($src_img);

       //return $filename_th;
       return;
    } //createThumb


    //Create name of thumbnail from filename
    function getThumbName(
                        $filename)
    {
        if (strpos($filename, "\\") > 0)
            $filename_th = "th_".substr(strrchr($filename, "\\"), 1);
        else
            $filename_th = "th_".$filename;

        return $filename_th;
    } //getThumbname


    //Definitions, bla
    $path       = yourdirectory/whatever;
    $filename = yourimage.jpg;

    //Create thumb thumb of image
    createThumb($path, $filename);

*****************************************
tell me, if you tried and there was an error.
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Very simple problem - I did say to keep the function as it was, but it seems like you removed it! Paste the code from my last post below the function definition of resampimagejpg. That should work.
0
 

Author Comment

by:theprankstanator
Comment Utility
Thanks Squinky - all is working now.

You both rock!! I am not sure how to do the points as you have both helped me.... suggestions?
0
 
LVL 4

Expert Comment

by:kolpdc
Comment Utility
;) if you like, divide them the way you like...
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Yup, it's up to you what you think is fair.
0
 

Author Comment

by:theprankstanator
Comment Utility
Well, you both rock, thanks heaps.

Christian
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
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…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

744 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

18 Experts available now in Live!

Get 1:1 Help Now