Image crop and resize on upload

Posted on 2007-10-13
Last Modified: 2008-09-28

Searching in experts-exhange answers I found the php part of the following code(and modify it a bit):
$tpath = "C:/AppServ/www/personal_website/03/resize/uploads";//thumbnails path
     //check for uploaded file from form
     if ($_FILES['image1'] != "") {
     //name of uploaded image selected from form
     $img = $_FILES['image1']['tmp_name'];
     //name for created thumbnail
     $img_name = $_FILES['image1']['name'];
        $dimensions = GetImageSize($img);
    $thname = "$tpath/$img_name";
    $img2 = ImageCreateFromJPEG($img);
    //set new proportional height $nh and width $nw
    //if image is wider than it is tall
    if ($w < $h){
    $nw = 100;
    $nh = $h * $nw / $w;
    $sw = 0;
    $sh = ($nh/2)-50;
    //if image is taller than it is wide
    if ($w > $h){
    $nh = 100;
    $nw = $w * $nh / $h;
    $sh = 0;
    $sw = ($nw/2)-50;
    //if image is square
    if ($w == $h){
    $nw = 100;
    $nh = 100;
    $sw = 0;
    $sh = 0;
    $thumb = imagecreatetruecolor(100,100);
    $thumb1 = imagecreatetruecolor($nw,$nh);
    imagecopyresized ($thumb, $thumb1, 0, 0, $sw, $sh, 100, 100, 100, 100);
    ImageJPEG($thumb,$thname,90); //stores thumbnail
    //store the full-size image
   copy($_FILES['myfile']['tmp_name'], "C:/AppServ/www/personal_website/03/resize/uploads".$_FILES['myfile']['name'])
          or die("Couldn't copy the full-size file!");
    } else {
         die("No input file specified");
<form action="resize.php"  method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="image1"  />
<input type="hidden" name="submit_img" value="1" />
<input type="submit" name="submit" value="submit" />

I have a directory called uploads and there I want to store the uploaded files (not-edited). I also have a directory called thumbs(inside uploads) where I want to store the edited images. Also I want to be able to adjust the crop, resize dimensions dynamically with some text fields asking the user to put the new image dimensions instead from having to edit the php file
Can you provide a complete php code for the above?
Question by:universe3d
    LVL 3

    Expert Comment

    Besides the missing "<?php" tag at the top and the potential need to change the paths to which the images are uploaded that code looks fine. Have you tried it yet?

    Author Comment

    Thanks, I fixed it but from what I see this script does not display correctly the images (I am refering to the quality), so I found the following script that does the job (with some problems):


     //File upload
     $image = $_FILES['image1']['name'];
     $image2 = $_FILES['image2']['name'];
     $image3 = $_FILES['image3']['name'];

          $root_path = $_SERVER['DOCUMENT_ROOT'];
          $path1 = $root_path."/personal_website/03/resize/uploads/".$image;
          $path2 = $root_path."/personal_website/03/resize/uploads/".$image2;
          $path3 = $root_path."/personal_website/03/resize/uploads/".$image3;
          move_uploaded_file($_FILES['image1']['tmp_name'], $path1);
          move_uploaded_file($_FILES['image2']['tmp_name'], $path2);
          move_uploaded_file($_FILES['image3']['tmp_name'], $path3);

    <form action="resize_system.php"  method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="image1"  />
    <input type="hidden" name="submit_img" value="1" />
    <input type="submit" name="submit" value="submit" />
    if ($_POST['submit_img'] == 1){
    // The file
    $filein = "uploads/".$image; // File in
    $fileout = "uploads/thumb_".$image; // Fileout - optional

    $imagethumbsize_w = 90; // thumbnail size (area cropped in middle of image)
    $imagethumbsize_h = 30; // thumbnail size (area cropped in middle of image)

    //Author Alan Reddan Silverarm Solutions
    //Date 27/01/2005
    //Function that works well with images.
    //It takes the image and reduces its size to best fit. i.e If you have an image
    //that is 200 X 100 and you want a thumbnail of 75 X 50,
    //it first resizes the image to 100 X 50
    //and then takes out a portion 75 X 50 from then center of the input image.
    //So loads of image information is retained.
    //The corollary also holds if your input image is 100 X 200
    //it first resizes image to 75 X 150 and then takes out a
    //portion 75 X 75 from the centre
    // The advantage here is that function decides on whether
    //resize is by width or height itself.
    //it also decides whether to use the height or the width as the base start point
    //in the case that athumbnail is rectangular

    function resize_then_crop( $filein,$fileout,

    // Get new dimensions
    list($width, $height) = getimagesize($filein);
    $new_width = $width * $percent;
    $new_height = $height * $percent;

       if(preg_match("/.jpg/i", "$filein"))
           $format = 'image/jpeg';
       if (preg_match("/.gif/i", "$filein"))
           $format = 'image/gif';
       if(preg_match("/.png/i", "$filein"))
           $format = 'image/png';
               case 'image/jpeg':
               $image = imagecreatefromjpeg($filein);
               case 'image/gif';
               $image = imagecreatefromgif($filein);
               case 'image/png':
               $image = imagecreatefrompng($filein);

    $width = $imagethumbsize_w ;
    $height = $imagethumbsize_h ;
    list($width_orig, $height_orig) = getimagesize($filein);

    if ($width_orig < $height_orig) {
      $height = ($imagethumbsize_w / $width_orig) * $height_orig;
    } else {
        $width = ($imagethumbsize_h / $height_orig) * $width_orig;

    if ($width < $imagethumbsize_w)
    //if the width is smaller than supplied thumbnail size
    $width = $imagethumbsize_w;
    $height = ($imagethumbsize_w/ $width_orig) * $height_orig;;

    if ($height < $imagethumbsize_h)
    //if the height is smaller than supplied thumbnail size
    $height = $imagethumbsize_h;
    $width = ($imagethumbsize_h / $height_orig) * $width_orig;

    $thumb = imagecreatetruecolor($width , $height);
    $bgcolor = imagecolorallocate($thumb, $red, $green, $blue);  
    ImageFilledRectangle($thumb, 0, 0, $width, $height, $bgcolor);
    imagealphablending($thumb, true);

    imagecopyresampled($thumb, $image, 0, 0, 0, 0,
    $width, $height, $width_orig, $height_orig);
    $thumb2 = imagecreatetruecolor($imagethumbsize_w , $imagethumbsize_h);
    // true color for best quality
    $bgcolor = imagecolorallocate($thumb2, $red, $green, $blue);  
    ImageFilledRectangle($thumb2, 0, 0,
    $imagethumbsize_w , $imagethumbsize_h , $white);
    imagealphablending($thumb2, true);

    $w1 =($width/2) - ($imagethumbsize_w/2);
    $h1 = ($height/2) - ($imagethumbsize_h/2);

    imagecopyresampled($thumb2, $thumb, 0,0, $w1, $h1,
    $imagethumbsize_w , $imagethumbsize_h ,$imagethumbsize_w, $imagethumbsize_h);

    // Output
    //header('Content-type: image/gif');
    //imagegif($thumb); //output to browser first image when testing

    if ($fileout !="")imagegif($thumb2, $fileout); //write to file

    resize_then_crop( $filein,$fileout,$imagethumbsize_w,$imagethumbsize_h,/*rgb*/"255","255","255");


    So this script works fine but the problem is that I want to dynamically upload 3 images (not only one) and then the script resize them as it do with one image. So can you help for the above by giving me some code?
    LVL 3

    Accepted Solution

    Just add this below the first resize_then_crop() call.

    resize_then_crop( "uploads/".$image2,"uploads/thumb_".$image2,$imagethumbsize_w,$imagethumbsize_h,/*rgb*/"255","255","255");
    resize_then_crop( "uploads/".$image3,"uploads/thumb_".$image3,$imagethumbsize_w,$imagethumbsize_h,/*rgb*/"255","255","255");

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Training Course: Android App Development

    This course will involve creating widgets, customize list view, grid view, spinners, etc. Creating applications using audio, video, and SQLite database. Ending with publication on Google Play.

    Foreword (May 2015) This web page has appeared at Google.  It's definitely worth considering! How to Know You are Making a Difference at EE In August, 2013, one …
    Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
    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…
    Learn how to set-up PayPal payment integration in your Wufoo form. Allow your users to remit payment through PayPal upon completion of your online form. This is helpful for collecting membership payments, customer payments, donations, and more.

    760 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

    12 Experts available now in Live!

    Get 1:1 Help Now