?
Solved

Resize images while uploading

Posted on 2006-06-03
18
Medium Priority
?
578 Views
Last Modified: 2006-11-18
Hi experts, fairly tricky question here.

I've got a web page with 3 input boxes on it and corresponding 'browse' buttons. This allows users to upload 3 JPEG files onto my server. If the files are >2Mb or not in JPEG format, the file is rejected. Each customer has a unique number and each advertisement has a unique number.

When the images are uploaded to my server, they are renamed. So if the advertisement number is 1000, my renamed files are:   1000_1.jpg (for picture 1), 1000_2.jpg (for picture 2), 1000_3.jpg (for picture 3).

The path to each file is written to the corresponding database field. All works perfectly.

BUT...what I need to do is resize the images while theyre being uploaded to 300 pixels in height and adjust the width to keep them in proportion.

Can someone please tell me how to go about this? Here's my code, thanks in advance.

<?php

session_start();

include 'testlogin.php';

$currentcustomer = $_SESSION['currentcustomer'];

include('connect.php');
$dbLinkID = mysql_connect("localhost",$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

?>

   <form method="POST" enctype="multipart/form-data" name="addcar" action="<?php echo $SELF_PHP; ?>"><p>
   <?php
      $query = "SELECT Max(Advertisement_No) AS MaxOfAdvertisement_No FROM advertisements WHERE Customer_No =$currentcustomer";

      $result = mysql_query($query);
      $get_info = mysql_fetch_array($result);

      $currentadvertisement=$get_info['MaxOfAdvertisement_No'];
?>


      <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
      <CENTER>
      You can upload your photographs here which must be in JPG format and under 2Mb in size. <P>
      The photograph uploaded in the first box below will be your main one.<P>

                          Photo 1: <input type="file" name="file[1]" size="75" maxlength="75"><br>
                          Photo 2: <input type="file" name="file[2]" size="75" maxlength="75"><br>
                          Photo 3: <input type="file" name="file[3]" size="75" maxlength="75"><br><br>

      <input type="submit" value="Upload my photographs"><P><BR><B><U>Results:</U></B><P>

      <TABLE>
      <TR>
      <TD>
<?php

     function upload_file ($upload_path, $fname, $fileid)
     {
          $problem = TRUE;

          switch ($_FILES['file']['error'][$fileid])
          {
              case UPLOAD_ERR_FORM_SIZE:
                   $error = "The server has rejected your photograph because it exceeds 2Mb";
                   break;
              case UPLOAD_ERR_NO_FILE:
                   $error = "No file was uploaded";
                   break;
              default:
                   $error = "";
          }


          //$fname = $_FILES['file']['name'][$fileid];
          $dest = $upload_path.$fname;
          $tmpfile = $_FILES['file']['tmp_name'][$fileid];

          if ($tmpfile)
          {
            $info = getimagesize($tmpfile);
            $ftype = $info['mime'];

              if ($ftype != "image/jpeg")
              {
                    $error = "Please choose a JPEG file and try again...";
                    $problem = TRUE;
              }
              else
              {
                              if (copy($tmpfile,$dest))
                              {
                                    $problem = FALSE;
                              }
                              else
                              {
                                    $problem = TRUE;
                              }
                    }
          }

          return array($problem, $error);
     }



     // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
     // of $_FILES.

          $form = TRUE;
     $upload_path = "/home/server/public_html/liveimages/";            //upload path for storing files
     $upload_path_db = "/liveimages/";                                          //upload path to write to database

     $fname = $currentadvertisement;



     for ($i=1;$i<4;$i++)
     {
          list($problem, $error) = upload_file ($upload_path, $currentadvertisement."_"."$i".".jpg", $i);
          if (!$problem)
          {
               $fname++;

                 // connect to database
                     include('connect.php');
                     $dbLinkID = mysql_connect("localhost",$username,$password);
                     @mysql_select_db($database) or die( "Unable to select database");

                     $phototoupdate='Photo'.$i;
                     $photopath=$upload_path_db.$currentadvertisement."_".$i.".jpg";

                     $query2 = "UPDATE advertisements SET $phototoupdate = '$photopath' WHERE Advertisement_No = $currentadvertisement";
                        mysql_query($query2);

                  echo Photo." $i".": "."Successful upload"."<br>";
          }
          else
               echo Photo." $i".": ".$error."<br>";
     }

  // close connection
 mysql_close($dbLinkID);

?>

      </TR>
      </TABLE>

<input type="submit" name="submit" value="Add this car and checkout" onClick="document.addcar.action='gotocheckout.php'">&nbsp&nbsp&nbsp&nbsp



</FORM>
</body>
</html>
0
Comment
Question by:andrewf10
  • 10
  • 7
18 Comments
 
LVL 16

Accepted Solution

by:
dr_dedo earned 1880 total points
ID: 16825059
try this
<?php

session_start();

include 'testlogin.php';

$currentcustomer = $_SESSION['currentcustomer'];
include('connect.php');
$dbLinkID = mysql_connect("localhost",$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

?>

   <form method="POST" enctype="multipart/form-data" name="addcar" action="<?php echo $SELF_PHP; ?>"><p>
   <?php
     $query = "SELECT Max(Advertisement_No) AS MaxOfAdvertisement_No FROM advertisements WHERE Customer_No =$currentcustomer";

     $result = mysql_query($query);
     $get_info = mysql_fetch_array($result);

     $currentadvertisement=$get_info['MaxOfAdvertisement_No'];
?>


     <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
     <CENTER>
     You can upload your photographs here which must be in JPG format and under 2Mb in size. <P>
     The photograph uploaded in the first box below will be your main one.<P>

                      Photo 1: <input type="file" name="file[1]" size="75" maxlength="75"><br>
                      Photo 2: <input type="file" name="file[2]" size="75" maxlength="75"><br>
                      Photo 3: <input type="file" name="file[3]" size="75" maxlength="75"><br><br>

     <input type="submit" value="Upload my photographs"><P><BR><B><U>Results:</U></B><P>

     <TABLE>
     <TR>
     <TD>
<?php

     function upload_file ($upload_path, $fname, $fileid)
     {
          $problem = TRUE;

          switch ($_FILES['file']['error'][$fileid])
          {
              case UPLOAD_ERR_FORM_SIZE:
                   $error = "The server has rejected your photograph because it exceeds 2Mb";
                   break;
              case UPLOAD_ERR_NO_FILE:
                   $error = "No file was uploaded";
                   break;
              default:
                   $error = "";
          }


          //$fname = $_FILES['file']['name'][$fileid];
          $dest = $upload_path.$fname;
             $tmpfile= $_FILES['file']['tmp_name'][$fileid];

          if ($tmpfile)
          {
            $info = getimagesize($tmpfile);
            $ftype = $info['mime'];

              if ($ftype != "image/jpeg")
              {
                    $error = "Please choose a JPEG file and try again...";
                    $problem = TRUE;
              }
              else
              {
            $src = imagecreatefromjpeg($tmpfile);
            list($width,$height)=getimagesize($tmpfile);
            $newwidth=300;
            $newheight=($height/$width)*300; // to maintain aspect ratio
            $tmp=imagecreatetruecolor($newwidth,$newheight);            
            imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
            imagejpeg($tmp,$filename,100);
            

                         if (imagejpeg($tmp,$dest,100))
                         {
                              $problem = FALSE;
                        imagedestroy($src);
                        imagedestroy($tmp);
                         }
                         else
                         {
                              $problem = TRUE;
                         }
                 }
          }

          return array($problem, $error);
     }



     // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
     // of $_FILES.

         $form = TRUE;
     $upload_path = "/home/server/public_html/liveimages/";          //upload path for storing files
     $upload_path_db = "/liveimages/";                                   //upload path to write to database

     $fname = $currentadvertisement;



     for ($i=1;$i<4;$i++)
     {
          list($problem, $error) = upload_file ($upload_path, $currentadvertisement."_"."$i".".jpg", $i);
          if (!$problem)
          {
               $fname++;

                 // connect to database
                  include('connect.php');
                  $dbLinkID = mysql_connect("localhost",$username,$password);
                  @mysql_select_db($database) or die( "Unable to select database");

                  $phototoupdate='Photo'.$i;
                  $photopath=$upload_path_db.$currentadvertisement."_".$i.".jpg";

                  $query2 = "UPDATE advertisements SET $phototoupdate = '$photopath' WHERE Advertisement_No = $currentadvertisement";
                    mysql_query($query2);

               echo Photo." $i".": "."Successful upload"."<br>";
          }
          else
               echo Photo." $i".": ".$error."<br>";
     }

  // close connection
 mysql_close($dbLinkID);

?>

     </TR>
     </TABLE>

<input type="submit" name="submit" value="Add this car and checkout" onClick="document.addcar.action='gotocheckout.php'">&nbsp&nbsp&nbsp&nbsp



</FORM>
</body>
</html>
0
 
LVL 11

Assisted Solution

by:neester
neester earned 120 total points
ID: 16825597
Just a note - that solution above is great.

BUT > to the question asker.

The width is still a free variable.

ie.
I could upload a picture with 2000 * 100;
that means you would upload and resize that to 6000 * 300;
which is extreemly wide.
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16826898
Excellent answer dr_dedo and good point neester, thanks ever so much.

OK I tweaked the code so that the width is the variable and the height is hardcoded. Question I have is...what does the value of 100 relate to? Is it the image quality?

I also added a simple IF statement to check that the Width divided by the Height is below 2, otherwise dont upload.

All works perfectly EXCEPT one thing.

Instead of saying "Successful upload" it outputs the full file in characters! Here's the start of it:

?JFIF?CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 100 ???,&#131;"? ?}!1AQa"q2???#B??R&#1136;$3br? %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz???????????????????????????????????&#131;&#261;&#391;&#521;&#658;&#1236;&#1366;&#1496;&#1626;&#6307;&#18790;&#31273;&#44146;&#56211;&#56694;?? ?w!1AQaq"2?B????#3R&#55318;&#56498;&#1098;$4&#6513;&'()*
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 16

Expert Comment

by:dr_dedo
ID: 16828914
yes, it is the quality, have a look here:
http://www.php.net/manual/fi/function.imagejpeg.php

did the code work fine then produced these stuff afterwards, or produced it from the start ??
please post your code
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16832417
I thought it may have been the changes I made to the code so I reverted to copying and pasting your exact code.

The image uploads and resizes perfectly, the path gets written to the database perfectly and the message does actually inform the user that the upload was successful.

BUT, all that jibberish keeps appearing. Just to be sure, I went back to my original code (that I pasted in my question) and that jibberish does not appear! Strange or what?
0
 
LVL 16

Assisted Solution

by:dr_dedo
dr_dedo earned 1880 total points
ID: 16832558
change
imagejpeg($tmp,$filename,100);
to
imagejpeg($tmp,$fname,100);

0
 
LVL 2

Author Comment

by:andrewf10
ID: 16832584
Great find, works perfectly. Thanks a million, really appreciate the help
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16832724
I just see that the image is being created in 2 different location on my server:

/liveimages/  (this is correct)  and also the root (which shouldnt be the case)

Would I need to add an unlink at the end?
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16832812
i thought you want to preserve both, the orginal and the resized one
this line copies the orginal pics
 if (copy($tmpfile,$dest))
remove that block to keep only the resized pic
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16832888
But I dont have that line anymore...thats why I'm miffed!
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16832909
Even your original code (albeit with the $fname correction of 40 minutes ago) produces the duplicate images
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16832960
i know my code creat duplicat images, i made it that way to preserve orginal image, but you don't have this line anymore (copy($tmpfile,$dest))!! image copying process here is done via imagejpeg($tmp,$filename,100);
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16833110
But how does my code know to create the duplicate image???  OK it reads the $dest variable and writes to the /liveimages/ folder. But where it gets the instruction to copy to the root...thats where I'm lost!

It's not actually preserving the original image, it's resizing it into one folder and then duplicating it into the other. I need it to do neither...sounds like I'll have to do an unlink.
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16833179
seems to be it then! unlink it!
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16833652
Will the double copying and then deletion afterwards slow things down for the end-user?
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16834255
who u mean end user ? ur client to whome you are designing that or the site user ?? if u mean site user, then i won't matter, but for the server itself, for sure there is an overload
why don't you post the code u r using now, may there is somthing i can do !
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16835215
The code I'm using for testing is the exact same as you posted in your first reply....with the $fname correction.

The Unlink works fine...I'm just concerned about its lack of efficiency.
0
 
LVL 2

Author Comment

by:andrewf10
ID: 16840354
This method seems to be a standard thing actually, I'll stick with it as is!

Thanks again for the help
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month16 days, 17 hours left to enroll

864 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