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";
    }
qwertqAsked:
Who is Participating?
 
alextr2003frConnect With a Mentor Commented:
yeah good idea, thus your database will be more compact and better
here is a working solution though :
...
         // 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 (NEW PART)
         $db_image = addslashes (fread (fopen ($file_name, "r"), filesize ($file_name))); //read the image into $db_image

         if (in_array (strtolower ($file_type), $image_types)) {
           // new query too with $db_image instead of $file_name
           $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); //delete the file
...
/////////////////////////////////////////////////////////////////

for your second solution, using simple upload it will be something like :

  $uploaddir = root_path."/uploads/";
  $local_filename = $_FILES['resume_file']['name'];
  $unique_filename = uniqid('resume_').'.jpg';
  $uploadfile = $uploaddir . basename($unique_filename);
  $result = move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);

  then in your database query use '$unique_filename' as name of the file
0
 
qwertqAuthor Commented:
Proportionately i mean....
0
 
alextr2003frCommented:

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);
?>
0
Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

 
qwertqAuthor Commented:
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.
0
 
alextr2003frCommented:
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"];
0
 
qwertqAuthor Commented:
ok, let me try i guess
0
 
alextr2003frCommented:
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";
    }
?>
0
 
alextr2003frCommented:
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.
0
 
qwertqAuthor Commented:
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
0
 
alextr2003frCommented:
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
0
 
qwertqAuthor Commented:
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
0
 
alextr2003frCommented:
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
0
 
qwertqAuthor Commented:
i do not want to save the file on my server.
0
 
alextr2003frCommented:
you can delete it after resizing and putting it in your database
0
 
qwertqAuthor Commented:
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
0
 
alextr2003frCommented:
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);
}
0
 
alextr2003frCommented:
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.
0
 
qwertqAuthor Commented:
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?
0
 
alextr2003frCommented:
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.
0
 
qwertqAuthor Commented:
how would i know the correct path? it appears to be generating '/usr/tmp/php9rZW19' at random
0
 
alextr2003frCommented:
try /usr/tmp/
0
 
qwertqAuthor Commented:
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
0
 
alextr2003frCommented:
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
0
 
alextr2003frCommented:
try with another jpeg file instead of the gif file
0
 
qwertqAuthor Commented:
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?
0
 
alextr2003frCommented:
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.
0
 
qwertqAuthor Commented:
but your script is not using GD its doing
imagecreatefromjpeg

that would not work with a gif, right?
0
 
alextr2003frCommented:
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
0
 
qwertqAuthor Commented:
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";
  }
0
 
alextr2003frCommented:
to prevent it from outputing in the browser delete the following line :
         // Output
         imagejpeg($newImage);
0
 
qwertqAuthor Commented:
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)
0
 
alextr2003frCommented:
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'...
0
 
alextr2003frCommented:
0
 
qwertqAuthor Commented:
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)
0
 
alextr2003frCommented:
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
0
 
alextr2003frCommented:
Warning: imagejpeg(): Invalid filename ''
what are you putting in $filename? try to write some file name in it
0
 
alextr2003frCommented:
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

 
0
 
qwertqAuthor Commented:
         // 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
0
 
alextr2003frCommented:
add this to resize if width > 300 px
           $newwidth  = 300;
           $newheight = round((30000/$width)*$height/100,0);
0
 
alextr2003frCommented:
so the file made in $filename is not valid?
0
 
qwertqAuthor Commented:
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);
      }
0
 
alextr2003frCommented:
ok checking it
0
 
qwertqAuthor Commented:
its missing an

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

thanks!!
0
 
alextr2003frCommented:
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);
0
 
qwertqAuthor Commented:
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.
0
 
alextr2003frCommented:
try to store $newImage instead of $file_name
0
 
alextr2003frCommented:
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())";
0
 
qwertqAuthor Commented:
"Resource id #5" stored in db instead of image....
0
 
alextr2003frCommented:
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())";
0
 
qwertqAuthor Commented:
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....
0
 
alextr2003frCommented:
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.
0
 
qwertqAuthor Commented:
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...
0
 
alextr2003frCommented:
you are welcome I'll try check it again and tell you the news
0
 
qwertqAuthor Commented:
what is this command? (found it in the example you linked above)

 $folder = "home/usr/website/images";
  @copy("$filep" , "$folder/$filep_name");
0
 
alextr2003frCommented:
it is just another way to copy the file into the image folder (instead of move upload)
0
 
alextr2003frCommented:
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);
...
0
 
qwertqAuthor Commented:
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
0
 
alextr2003frCommented:
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.
0
 
alextr2003frCommented:
show me your new code from the // RESIZE IMAGE part please
0
 
qwertqAuthor Commented:
       // 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
0
 
qwertqAuthor Commented:
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
0
 
qwertqAuthor Commented:
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.
0
 
alextr2003frCommented:
You are welcome :)
0
All Courses

From novice to tech pro — start learning today.