PHP Resize Image

Hello,

I have the following line in my image upload script and I would like to make it so that the image is uploaded proportionately instead of a standard crop.

               $newFile = Resize($tmpFile, 640, 480,$upload_path);

Any help would be great.

Thanks,
Matt
function Resize($tmpFile, $w, $h, $dest)
   {
        $resource = imagecreatefromjpeg($tmpFile);
        $sw = imagesx($resource);
        $sh = imagesy($resource);
        $ar = $sw/$sh;
        $tar = $w/$h;
        if($ar >= $tar)
        {
                  $x1 = round(($sw - ($sw * ($tar/$ar)))/2);
                  $x2 = round($sw * ($tar/$ar));
                  $y1 = 0;
                  $y2 = $sh;
        }
        else
        {
                  $x1 = 0;
                  $y1 = 0;
                  $x2 = $sw;
                  $y2 = round($sw/$tar);
        }
        if(!($slate = @imagecreatetruecolor($w, $h)))
        {
               return false;
        }
        imagecopyresampled($slate, $resource, 0, 0, $x1, $y1, $w, $h, $x2, $y2);
        $file_name = date('hism');
        $file_name.=genName().'.jpg';
        $full_path = $dest . $file_name;
        if(file_exists($full_path)) {
            $patch = genName();  
            $full_path = $file_name.'_'.$patch.'.jpg';
            $file_name .= $patch.'.jpg';
        }
        imagejpeg($slate, $full_path, 80);
        imagedestroy($slate);
        imagedestroy($resource);
        return $file_name;
}

Open in new window

LVL 1
movieprodwAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

tdotCommented:
Hi matt,

Ive added 2 new functions to handle your request... let me know how it worked out.


<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
ini_set("memory_limit","64M");

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
ini_set("memory_limit","64M");

include ('./db.php');  
//IF WIDTH IS GREATER
function resizew($jpgFile, $width,$dest) {
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($jpgFile);
$height = (int) (($width / $width_orig) * $height_orig);
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($jpgFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
$i=0;
$file_name = date('h:i:s:m');
$file_name.=genName().'.jpg';
$full_path = $dest . $file_name;
while(true){
 if(file_exists($full_path)) {
   $patch = genName();  
   $file_name = date('h:i:s:m').$patch.'.jpg';
   $full_path = $dest.$file_name;
 }else{
   break;
 }
}// Output
imagejpeg($image_p, $full_path, 80);
imagedestroy($image_p);
imagedestroy($image);
return $file_name;
}

//IF HEIGHT IS GREATER
function resizeh($jpgFile, $height,$dest) {
     // GET NEW DIMENSION..
     
        list($width_orig, $height_orig) = getimagesize($jpgFile);
      $width = (int) (($height / $height_orig) * $width_orig);
      // RESAMPLE
      $image_p = imagecreatetruecolor($width, $height);
      $image = imagecreatefromjpeg($jpgFile);
      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
      $i=0;
     //FILE NAME AND LOCATION
      $file_name = date('h:i:s:m');
        $file_name.=genName().'.jpg';
        $full_path = $dest . $file_name;
        while(true){
         if(file_exists($full_path)) {
            $patch = genName();  
            $file_name = date('h:i:s:m').$patch.'.jpg';
            $full_path = $dest.$file_name;
         }else{
           break;
        }
     }
   // Output
  imagejpeg($image_p, $full_path, 80);
  imagedestroy($image_p);
  imagedestroy($image);
  return $file_name;
}


function genName($length = 8){  
    $string = "";
    //character that can be used
    $possible = "0123456789bcdfghjkmnpqrstvwxyz";
    for($i=0;$i < $length;$i++)
    {
        $char = substr($possible, rand(0, strlen($possible)-1), 1);
       
        if (!strstr($string, $char))
        {
            $string .= $char;
        }
    }

    return $string;
}

function Resize($tmpFile, $w, $h, $dest)
   {
        $resource = imagecreatefromjpeg($tmpFile);
        $sw = imagesx($resource);
        $sh = imagesy($resource);
        $ar = $sw/$sh;
        $tar = $w/$h;
        if($ar >= $tar)
        {
                  $x1 = round(($sw - ($sw * ($tar/$ar)))/2);
                  $x2 = round($sw * ($tar/$ar));
                  $y1 = 0;
                  $y2 = $sh;
        }
        else
        {
                  $x1 = 0;
                  $y1 = 0;
                  $x2 = $sw;
                  $y2 = round($sw/$tar);
        }
        if(!($slate = @imagecreatetruecolor($w, $h)))
        {
               return false;
        }
        imagecopyresampled($slate, $resource, 0, 0, $x1, $y1, $w, $h, $x2, $y2);
        $file_name = date('h:i:s:m');
        $file_name.=genName().'.jpg';
        $full_path = $dest . $file_name;
        if(file_exists($full_path)) {
            $patch = genName();  
            $file_name = date('h:i:s:m').$patch.'.jpg';
            $full_path = $dest.$file_name;
        }
        imagejpeg($slate, $full_path, 80);
        imagedestroy($slate);
        imagedestroy($resource);
        return $file_name;
}
echo'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="myfile[0]" /><br>
<input type="file" name="myfile[1]" /><br>
<input type="file" name="myfile[2]" /><br>
<input type="file" name="myfile[3]" /><br>
<input type="file" name="myfile[4]" /><br>
<input type="file" name="myfile[5]" /><br>
<input type="file" name="myfile[6]" /><br>
<input type="file" name="myfile[7]" /><br>
<input type="file" name="myfile[8]" /><br>
<input type="hidden" value="true" name="submitted" />
<input type="submit" value="Send" />
</p>
</form>
</body>
</html>';
$submitted=@$_POST['submitted'];
if($submitted=='true'){
    $upload_path = "../pics/test/";
      $height = '70'; //set image allowed height
      $width = '70'; //set allowed width
      $count=0;
      $size = array();
      foreach ($_FILES["myfile"]["name"] as $key => $error) {
         $tmpFile = $_FILES["myfile"]["tmp_name"][$key];
         $name = $_FILES["myfile"]["name"][$key];
         if($tmpFile!=''){
              $uploaded=true;
              $count+=1;
              $file_type = $name;
          $file_type_length = strlen($file_type) - 3;
          $file_type = substr($file_type, $file_type_length);
            $file_type = strtolower($file_type);
          $files = array();
          $files[] = 'jpeg';
          $files[] = 'jpg';
          $files[] = 'gif';
          $files[] = 'png';
              // Search the array for the allowed file type
          $key = array_search($file_type, $files);
          if(!$key) {
            echo '<b>ILLEGAL FILE TYPE</b><br />';
            exit();
          }
            ;
             
             $size = getimagesize($tmpFile);
               if($size[0] > $size[1]){
                  $newFile =resizew($tmpFile, $width,$upload_path);
                  // IF WIDTH IS GREATER THAN HIEGHT
              }elseif( $size[0] < $size[1]) {
                  $newFile =resizeh($tmpFile, $height,$upload_path);
              }
              // BOTH SIDE ARE THE SAME SIZE THE PCITURE IS A SQUARE..
              else{
                  $newFile = resizeh($tmpFile, $height,$upload_path);
             }
         $newFile = Resize($tmpFile, 640, 480,$upload_path);
             $query = "INSERT INTO images (imageId)values('$newFile')"; //PUT IMAGE IN DBASE HERE
         mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());       
        }
  }
  if($uploaded){
       echo "($count) image(s) were uploaded";
       exit();
  }else{
          echo "No images were uploaded";
          exit();
  }
}

?>





0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
movieprodwAuthor Commented:
Hello again tdot!

I used it and what it did was created a very small thumbnail [1.4k] that was the correct proportionate and then it made the same larger file that was cropped. I only need one image that is proportionate with a max h/w of 640/480.
0
movieprodwAuthor Commented:
Hello,

I figured it out, there was a left over line at the bottom that was used to make the other file and I deleted that, I also just changed the allowed height and width.

Thanks so much again!
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
ini_set("memory_limit","64M");

include ('./db.php');  
//IF WIDTH IS GREATER
function resizew($jpgFile, $width,$dest) {
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($jpgFile);
$height = (int) (($width / $width_orig) * $height_orig);
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($jpgFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
$i=0;
$file_name = date('hism');
$file_name.=genName().'.jpg';
$full_path = $dest . $file_name;
while(true){
 if(file_exists($full_path)) {
   $patch = genName();  
   $file_name = date('hism').$patch.'.jpg';
   $full_path = $dest.$file_name;
 }else{
   break;
 }
}// Output
imagejpeg($image_p, $full_path, 80);
imagedestroy($image_p);
imagedestroy($image);
return $file_name;
}

//IF HEIGHT IS GREATER
function resizeh($jpgFile, $height,$dest) {
     // GET NEW DIMENSION..
     
        list($width_orig, $height_orig) = getimagesize($jpgFile);
      $width = (int) (($height / $height_orig) * $width_orig);
      // RESAMPLE
      $image_p = imagecreatetruecolor($width, $height);
      $image = imagecreatefromjpeg($jpgFile);
      imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
      $i=0;
     //FILE NAME AND LOCATION
      $file_name = date('hism');
        $file_name.=genName().'.jpg';
        $full_path = $dest . $file_name;
        while(true){
         if(file_exists($full_path)) {
            $patch = genName();  
            $file_name = date('hism').$patch.'.jpg';
            $full_path = $dest.$file_name;
         }else{
           break;
        }
     }
   // Output
  imagejpeg($image_p, $full_path, 80);
  imagedestroy($image_p);
  imagedestroy($image);
  return $file_name;
}


function genName($length = 8){  
    $string = "";
    //character that can be used
    $possible = "0123456789bcdfghjkmnpqrstvwxyz";
    for($i=0;$i < $length;$i++)
    {
        $char = substr($possible, rand(0, strlen($possible)-1), 1);
       
        if (!strstr($string, $char))
        {
            $string .= $char;
        }
    }

    return $string;
}

function Resize($tmpFile, $w, $h, $dest)
   {
        $resource = imagecreatefromjpeg($tmpFile);
        $sw = imagesx($resource);
        $sh = imagesy($resource);
        $ar = $sw/$sh;
        $tar = $w/$h;
        if($ar >= $tar)
        {
                  $x1 = round(($sw - ($sw * ($tar/$ar)))/2);
                  $x2 = round($sw * ($tar/$ar));
                  $y1 = 0;
                  $y2 = $sh;
        }
        else
        {
                  $x1 = 0;
                  $y1 = 0;
                  $x2 = $sw;
                  $y2 = round($sw/$tar);
        }
        if(!($slate = @imagecreatetruecolor($w, $h)))
        {
               return false;
        }
        imagecopyresampled($slate, $resource, 0, 0, $x1, $y1, $w, $h, $x2, $y2);
        $file_name = date('hism');
        $file_name.=genName().'.jpg';
        $full_path = $dest . $file_name;
        if(file_exists($full_path)) {
            $patch = genName();  
            $file_name = date('hism').$patch.'.jpg';
            $full_path = $dest.$file_name;
        }
        imagejpeg($slate, $full_path, 80);
        imagedestroy($slate);
        imagedestroy($resource);
        return $file_name;
}
echo'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="myfile[0]" /><br>
<input type="file" name="myfile[1]" /><br>
<input type="file" name="myfile[2]" /><br>
<input type="file" name="myfile[3]" /><br>
<input type="file" name="myfile[4]" /><br>
<input type="file" name="myfile[5]" /><br>
<input type="file" name="myfile[6]" /><br>
<input type="file" name="myfile[7]" /><br>
<input type="file" name="myfile[8]" /><br>
<input type="hidden" value="true" name="submitted" />
<input type="submit" value="Send" />
</p>
</form>
</body>
</html>';
$submitted=@$_POST['submitted'];
if($submitted=='true'){
    $upload_path = "./propertyImages/";
      $height = '480'; //set image allowed height
      $width = '640'; //set allowed width
      $count=0;
      $size = array();
      foreach ($_FILES["myfile"]["name"] as $key => $error) {
         $tmpFile = $_FILES["myfile"]["tmp_name"][$key];
         $name = $_FILES["myfile"]["name"][$key];
         if($tmpFile!=''){
              $uploaded=true;
              $count+=1;
              $file_type = $name;
          $file_type_length = strlen($file_type) - 3;
          $file_type = substr($file_type, $file_type_length);
            $file_type = strtolower($file_type);
          $files = array();
          $files[] = 'jpeg';
          $files[] = 'jpg';
          $files[] = 'gif';
          $files[] = 'png';
              // Search the array for the allowed file type
          $key = array_search($file_type, $files);
          if(!$key) {
            echo '<b>ILLEGAL FILE TYPE</b><br />';
            exit();
          }
            ;
             
             $size = getimagesize($tmpFile);
               if($size[0] > $size[1]){
                  $newFile =resizew($tmpFile, $width,$upload_path);
                  // IF WIDTH IS GREATER THAN HIEGHT
              }else if( $size[0] < $size[1]) {
                  $newFile =resizeh($tmpFile, $height,$upload_path);
              }
              // BOTH SIDE ARE THE SAME SIZE THE PCITURE IS A SQUARE..
              else{
                  $newFile = resizeh($tmpFile, $height,$upload_path);
             }
             $query = "INSERT INTO images (imageId)values('$newFile')"; //PUT IMAGE IN DBASE HERE
         mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());       
        }
  }
  if($uploaded){
       echo "($count) image(s) were uploaded";
       exit();
  }else{
          echo "No images were uploaded";
          exit();
  }
}

?>

Open in new window

0
movieprodwAuthor Commented:
Awesome as usual!
0
tdotCommented:
Glad i could help matt..
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development

From novice to tech pro — start learning today.