Link to home
Start Free TrialLog in
Avatar of qwertq
qwertq

asked on

resize image on upload

i have a php script that will upload an image and save it into a database...

i want to add a feature to this that will check the image's width and if its over 300px it will resize the image PORPOTANATLY to be 300px wide...

this is the part of the script that does the saving

      $image_types = Array ("image/bmp",
                        "image/jpeg",
                        "image/pjpeg",
                        "image/gif",
                        "image/x-png");
                       

    $userfile  = addslashes (fread (fopen ($_FILES["userfile"]["tmp_name"], "r"), filesize ($_FILES["userfile"]["tmp_name"])));
    $file_name = $_FILES["userfile"]["name"];
    $file_size = $_FILES["userfile"]["size"];
    $file_type = $_FILES["userfile"]["type"];

    if (in_array (strtolower ($file_type), $image_types)) {
     
      $query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$userfile', '$file_size', '$file_name', NOW())";
      $f1->query($query);
     
      echo "uploaded";
    }
Avatar of qwertq
qwertq

ASKER

Proportionately i mean....

1) use getimagesize to get your image size
2) use imagecopyresized to resize :

example at : http://fr.php.net/ImageCopyResized
<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreate($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb);
?>
Avatar of qwertq

ASKER

this looks like it is designed to be used for images stored on the server then displaying them. i would like to take the image that has been submited via form and resize prior to saving in database.
you can resize it with this procedure just before you put your image in the database after you get your file with $file_name = $_FILES["userfile"]["name"];
Avatar of qwertq

ASKER

ok, let me try i guess
An on the fly code, not tried yet, would look something like :

<?
$image_types = Array ("image/bmp",
                        "image/jpeg",
                        "image/pjpeg",
                        "image/gif",
                        "image/x-png");

$userfile  = addslashes (fread (fopen ($_FILES["userfile"]["tmp_name"], "r"), filesize ($_FILES["userfile"]["tmp_name"])));
$file_name = $_FILES["userfile"]["name"];
$file_size = $_FILES["userfile"]["size"];
$file_type = $_FILES["userfile"]["type"];

// Get sizes
list($width, $height) = getimagesize($file_name);
if ($width > 300) { //need resize?
  $percent = 0.5; //change to your resize rules
  $newwidth = $width * $percent;
  $newheight = $height * $percent;
} else {
  //keep same sizes
  $newwidth = $width;
  $newheight = $height;
}
// Load
$thumb = imagecreate($newwidth, $newheight);
$source = imagecreatefromjpeg($file_name);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb);

    if (in_array (strtolower ($file_type), $image_types)) {

      $query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$userfile', '$file_size', '$thumb', NOW())";
      $f1->query($query);

      echo "uploaded";
    }
?>
perhaps :
$query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$thumb', '$file_size', '$file_name', NOW())";
just look in what field you store your resized image and replace it by $thumb since it contains the resized image.
Avatar of qwertq

ASKER

still appears as if it is trying to access an actual file on the server...

Warning: getimagesize(question2.gif): failed to open stream: No such file or directory in /--REMOVED--/index.php on line 27

Warning: imagecreate(): Invalid image dimensions in /--REMOVED--/index.php on line 38

Warning: imagecreatefromjpeg(question2.gif): failed to open stream: No such file or directory in /--REMOVED--/index.php on line 39

Warning: imagecopyresized(): supplied argument is not a valid Image resource in /--REMOVED--/index.php on line 41

Warning: imagejpeg(): supplied argument is not a valid Image resource in /--REMOVED--/index.php on line 43
you need to check if the file is uploaded with this function :
is_uploaded_file
http://fr2.php.net/manual/en/function.is-uploaded-file.php
Avatar of qwertq

ASKER

is_uploaded_file returns true because the file IS an uploaded file. but it still is giving the same errors because getimagesize & etc still do not know it is not a physical file
then maybe you should move_uploaded_file to move the file in the right place
http://fr2.php.net/manual/en/function.move-uploaded-file.php
Avatar of qwertq

ASKER

i do not want to save the file on my server.
you can delete it after resizing and putting it in your database
Avatar of qwertq

ASKER

i can not get it to work right... i must be doing something wrong.
would you be able to offer up additional help?

points increased
yes, I am already helping you :) basically you will need to just add few
lines to handle the upload and delete it, it would look something like :
... code above...
$file_name = $_FILES["userfile"]["name"];
$file_size = $_FILES["userfile"]["size"];
$file_type = $_FILES["userfile"]["type"];

//uploading
$uploaddir = '/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  $file_name = $uploadfile;
  // Get sizes
  list($width, $height) = getimagesize($file_name);
  ... code above ....
  delete($uploadfile);
}
or without any verification on upload you can just specify your upload $directory = "/www/uploads" and do something like :
$file_name = $directory.$_FILES["userfile"]["name"];
because the problem it is that it cannot find the right path to the file.
Avatar of qwertq

ASKER

Warning: move_uploaded_file(/--REMOVED--/temp/586_birds_with_laptops.gif): failed to open stream: Permission denied in /--REMOVED--/index.php on line 29

Warning: move_uploaded_file(): Unable to move '/usr/tmp/php9rZW19' to '/--REMOVED--/temp/586_birds_with_laptops.gif' in /--REMOVED--t/index.php on line 29

you think my hosting company has some kind of restriction?
seems like you do not have the right to move it then try the second method without upload checking but just specify the /temp/ dir as path to the file.
Avatar of qwertq

ASKER

how would i know the correct path? it appears to be generating '/usr/tmp/php9rZW19' at random
try /usr/tmp/
Avatar of qwertq

ASKER

hi, i changed it to

  //SAVE TEMP FILE
  $uploaddir = '/usr/tmp/';
  $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

and now its throwing all kinds of other errors. have you actually tried the code you are proposing or is this all hypothetical?

Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: in /--REMOVED--/index.php on line 46

Warning: imagecreatefromjpeg(): '/usr/tmp/question2.gif' is not a valid JPEG file in /--REMOVED--/index.php on line 46

Warning: imagecopyresized(): supplied argument is not a valid Image resource in /--REMOVED--/index.php on line 48
ÿØÿàJFIFÿþ>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality ÿÛC    $.' ",#(7),01444'9=82<.342ÿÛC  2!!22222222222222222222222222222222222222222222222222ÿÀ"ÿÄ ÿĵ}!1AQa"q2‘¡#B±ÁRÑð$3br‚ %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ ÿĵw!1AQaq"2B‘¡±Á #3RðbrÑ $4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÚ ?ùþŠ( ÿÙuploaded
Fatal error: Call to undefined function: delete() in /--REMOVED--/index.php on line 59
the code it is generating is the code for a jpeg file, if you are storing your file in the database then you will need
an appropriate field to contain it, the code is theorical, but these should work in any case
1) uploading of file and few checkings
2) getting size resizing
3) saving in database
4) deleting the temporary file
try with another jpeg file instead of the gif file
Avatar of qwertq

ASKER

lol, whoops. it appears to be kind of working...
not throwing any errors until
Fatal error: Call to undefined function: delete() in /usr

however i did not realize that the solution you were suggesting did not work for .gif as well. i need it to work for jpg AND gif please. should i use gdimage?
Try unlink instead of delete. Normally GD should support gif images, maybe it is not a standard / bad formated version of a gif? try useing another gif instead. Gifs are only supported in GD versions older than gd-1.6 and newer than gd-2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is avaliable since PHP 4.3.9 and PHP 5.0.1, so maybe you should check if you do not need to upgrade the GD library also. For more information : http://fr2.php.net/gd
Alex.
Avatar of qwertq

ASKER

but your script is not using GD its doing
imagecreatefromjpeg

that would not work with a gif, right?
yes as the name says it should work just with jpegs :
http://fr.php.net/function.imagecreatefromjpeg

for gifs a imagecreatefromgif would be more appropriate :
http://fr3.php.net/imagecreatefromgif
Avatar of qwertq

ASKER

ok...  so i changed it to unlink. it is not erroring, but its not working. when you do the upload the screen shows the source code of the jpg (which it should not) and its not saving it to the database. here is my code:

            $image_types = Array ("image/bmp",
                        "image/jpeg",
                        "image/pjpeg",
                        "image/gif",
                        "image/x-png");
                       
            if (is_uploaded_file($userfile)) {

    $userfile  = addslashes (fread (fopen ($_FILES["userfile"]["tmp_name"], "r"), filesize ($_FILES["userfile"]["tmp_name"])));
    $file_name = $_FILES["userfile"]["name"];
    $file_size = $_FILES["userfile"]["size"];
    $file_type = $_FILES["userfile"]["type"];
   
    //SAVE TEMP FILE
    $uploaddir = '/usr/tmp/';
            $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
   
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
              
              $file_name = $uploadfile;
        
               // Get sizes
          list($width, $height) = getimagesize($file_name);
          if ($width > 300) { //need resize?
            $percent = 0.5; //change to your resize rules
            $newwidth = $width * $percent;
            $newheight = $height * $percent;
          } else {
            //keep same sizes
            $newwidth = $width;
            $newheight = $height;
          }
          // Load
          $newImage = imagecreate($newwidth, $newheight);
          $source = imagecreatefromjpeg($file_name);
          // Resize
          imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
          // Output
          imagejpeg($newImage);
          
          if (in_array (strtolower ($file_type), $image_types)) {
            
            $query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$newImage', '$file_size', '$file_name', NOW())";
            $f1->query($query);
            
      echo "<BR><BR> FILE UPLOADED";
    }
    unlink($uploadfile);
      }
   
  } else {
        echo "you must specify a file to upload";
  }
to prevent it from outputing in the browser delete the following line :
         // Output
         imagejpeg($newImage);
Avatar of qwertq

ASKER

ok, its not outputting now.

but its not storing the image in the database.

if i look at the database it shows "Resource id #5" in the field that should be the image. (its a BLOB)
try something like :
imagejpeg($newImage,$filename); and then save $filename in your database
or something like :
  $folder = '/usr/tmp/';
  copy($file_name , $folder."/".$file_name);
  VALUES(...'$file_name'...
Avatar of qwertq

ASKER

Warning: imagejpeg(): Invalid filename ''

         // PREPARE FOR INSERT
         imagejpeg($newImage,$filename);


it was inserting into the database before we did all this, so i do not think its anything suggested on the other PAQ
 
also i am just noticing this:

           $percent   = 0.5; //change to your resize rules
           $newwidth  = $width * $percent;
           $newheight = $height * $percent;

shouldn't it be $newwidth = '300';
and $newheight = (some kind of math to calculate new height)
yeah the $newwidth = 300;
and $newheight something like
pourcentage of old width in comparison with new width and apply same percentage to get the new height.
now the question is how to save your new file into the database
Warning: imagejpeg(): Invalid filename ''
what are you putting in $filename? try to write some file name in it
on the fly I think that your new height should be :
$newheight = round((300*100/$width)*$height/100,0);
                          % of new width          applying same % to height and rounding to an integer

 
Avatar of qwertq

ASKER

         // LOAD SAVED IMAGE
          $newImage    = imagecreate($newwidth, $newheight);
          $source      = imagecreatefromjpeg($file_name);
          // RESIZE IMAGE
          imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
          
          // PREPARE FOR INSERT
          imagejpeg($newImage,$filename);

that is what i am putting
add this to resize if width > 300 px
           $newwidth  = 300;
           $newheight = round((30000/$width)*$height/100,0);
so the file made in $filename is not valid?
Avatar of qwertq

ASKER

i do not know what it is supposed to be. i am totally lost here :)

here is the complete code:

            if (is_uploaded_file($userfile)) {

    $userfile  = addslashes (fread (fopen ($_FILES["userfile"]["tmp_name"], "r"), filesize ($_FILES["userfile"]["tmp_name"])));
    $file_name = $_FILES["userfile"]["name"];
    $file_size = $_FILES["userfile"]["size"];
    $file_type = $_FILES["userfile"]["type"];
   
    //SAVE TEMP FILE
    $uploaddir = '/usr/tmp/';
            $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
   
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
              
              $file_name = $uploadfile;
        
               // GET IMAGE SIZES
          list($width, $height) = getimagesize($file_name);
          if ($width > 300) { //need resize?
       $newwidth = '300';
            $percent   = $newwidth / $width;
            //$newheight = round((300*100/$width)*$height/100,0);
            $newwidth  = $width * $percent;
          } else {
            // DO NOT RESIZE
            $newwidth  = $width;
            $newheight = $height;
          }
          // LOAD SAVED IMAGE
          $newImage    = imagecreate($newwidth, $newheight);
          $source      = imagecreatefromjpeg($file_name);
          // RESIZE IMAGE
          imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
          
          // PREPARE FOR INSERT
          imagejpeg($newImage,$filename);
          
          if (in_array (strtolower ($file_type), $image_types)) {
            
            $query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$filename', '$file_size', '$file_name', NOW())";
            $f1->query($query);
            
      echo "<BR><BR> FILE UPLOADED";
    } else {
      echo "ERROR: The file format you uploaded is not allowed. Please upload .JPG or .GIF only.";
    }
    //unlink($uploadfile);
      }
ok checking it
Avatar of qwertq

ASKER

its missing an

} else {
 echo "you must specify a file to upload";
}

thanks!!
try this one :
...
         list($width, $height) = getimagesize($file_name);
         if ($width > 300) { //need resize?
           $newwidth = 300;
           //$percent   = $newwidth / $width;
           $newheight = round((300*100/$width)*$height/100,0);
           //$newwidth  = $width * $percent;
         } else {
           // DO NOT RESIZE
           $newwidth  = $width;
           $newheight = $height;
         }
         // LOAD SAVED IMAGE
         $newImage    = imagecreate($newwidth, $newheight);
         $source      = imagecreatefromjpeg($file_name);
         // RESIZE IMAGE
         imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

         // PREPARE FOR INSERT
         imagejpeg($newImage,$file_name);

         if (in_array (strtolower ($file_type), $image_types)) {
           $query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$file_name', '$file_size', '$file_name', NOW())";
           echo $query;
         }
      echo "<BR><BR> FILE UPLOADED";
    //unlink($uploadfile);
Avatar of qwertq

ASKER

closer...

that looks like its just storing the path to the image in the database. i want to store the actual picture in there, like i was doing in the code i pasted originally.
try to store $newImage instead of $file_name
in your query, something like :
$query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$newImage', '$file_size', '$file_name', NOW())";
Avatar of qwertq

ASKER

"Resource id #5" stored in db instead of image....
try something like :
$new_image = file_get_contents($file_name);
$query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$new_image', '$file_size', '$file_name', NOW())";
Avatar of qwertq

ASKER

that did not work either...

it might be easier for me to just not try to store the image in the database and store the image on server and the image information in the database....
yes it is the usual way to do it then just store the name of the file and files in a folder, your database will be not so heavy this way, if you store images in it, it will grow fast, but we are close to the solution since we just have to transform the result of $newImage into a database storable type.
Avatar of qwertq

ASKER

first i need to figure out why its not leting me move it. i can not store them in /usr/tmp/  i have dropped my hosting service and email asking why i do not have permission and i am going home i can resume this once i am home.

thanks for the help...
you are welcome I'll try check it again and tell you the news
Avatar of qwertq

ASKER

what is this command? (found it in the example you linked above)

 $folder = "home/usr/website/images";
  @copy("$filep" , "$folder/$filep_name");
it is just another way to copy the file into the image folder (instead of move upload)
I think the error was here :
instead of just passing the variable we have to read it like for the $_FILE above and format it for the database
here is the code :
...
         list($width, $height) = getimagesize($file_name);
         if ($width > 300) { //need resize?
           $newwidth = 300;
           //$percent   = $newwidth / $width;
           $newheight = round((300*100/$width)*$height/100,0);
           //$newwidth  = $width * $percent;
         } else {
           // DO NOT RESIZE
           $newwidth  = $width;
           $newheight = $height;
         }
         // LOAD SAVED IMAGE
         $newImage    = imagecreate($newwidth, $newheight);
         $source      = imagecreatefromjpeg($file_name);
         // RESIZE IMAGE
         imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

         // PREPARE FOR INSERT
         imagejpeg($newImage,$file_name);

         // REREAD THE NEW FILE FOR DB FORMAT
         $db_image = addslashes (fread (fopen ($file_name, "r"), filesize ($file_name)));        

         if (in_array (strtolower ($file_type), $image_types)) {

           $query = "INSERT INTO image_test (image_type, image, image_size, image_name, image_date) VALUES ( '$file_type','$db_image', '$file_size', '$file_name', NOW())";
           echo $query;
         }
      echo "<BR><BR> FILE UPLOADED";
      unlink($file_name);
...
Avatar of qwertq

ASKER

it looks like its still storing "resource id #15" for some reason. but do not worry about it. i think i will store them out of the db, i am worried about making my database bloated like you said will happen if i store a bunch of images in it.

i am going to try to use the @copy and see if it will let me have permission to save like move_image was not
did you replace your query by $db_image? because I just tested this solution and it works fine.
the new thing is it that it reads the $file_name into $db_image and strips the slashes
then puts the $db_image in the query.
show me your new code from the // RESIZE IMAGE part please
Avatar of qwertq

ASKER

       // RESIZE IMAGE
        imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

but again, i am going to try to alter this to save the file on my server instead of the datbase
ASKER CERTIFIED SOLUTION
Avatar of alextr2003fr
alextr2003fr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of qwertq

ASKER

its all working now! i had to set something so the script would run as my user instead of nobody.
even copies over to server now.

but the pictures are looking kinda weird....
BEFORE: http://www.louiswalch.com/resize_after/Flower1.JPG
AFTER: http://www.louiswalch.com/resize_after/Flower1-after%20resize.JPG

AFTER: http://www.louiswalch.com/resize_after/bow.jpg

on the second one the box was RED!! something weird is happening with the colors.

and also it looks like the quality of the jpgs is being lowers
Avatar of qwertq

ASKER

nevermind, i found this comment:

"Using imagecreate() combined with imagecreatefromjpeg() in PHP 4.3.0 and up creates wrong color jpeg's.

Use imagecreatetruecolor() instead of imagecreate() for right color images."

and it works right when i changed it.
thank you for your help! it appears to be working correctly.
You are welcome :)