PHP Image resize and crop

So I am a newbie at php. At this point I can reasonably piece together other people codes to get where I want to go but I am having a big problem with getting images to resize and crop to specific dimensions. I want all my images to be the exact same size for a photo gallery and once they click the thumbnail the whole image will pop up. so I made an uploader that also creates a thumbnail with a height of 200px but I want to also zoom in a bit and crop so that the final image is height 200 width 280. How would I do that so that even if I upload a very tall  thin photo the thumbnail will still come out clear an unstretched with the 200x280 size?

Script included below
<?php
 if(isset($_POST['Submit']))
 {
     $size = 200; // the thumbnail height
     $filedir = 'pics/'; // the directory for the original image
     $thumbdir = 'pics/'; // the directory for the thumbnail image
     $prefix = 'small_'; // the prefix to be added to the original name
     $maxfile = '3000000';
     $mode = '0666';
     $picname = $_POST['picname'];
     $userfile_name = $_FILES['image']['name'];
     $userfile_tmp = $_FILES['image']['tmp_name'];
     $userfile_size = $_FILES['image']['size'];
     $userfile_type = $_FILES['image']['type'];
     if (isset($_FILES['image']['name'])) 
     {
         $prod_img = $filedir.$userfile_name;
         $prod_img_thumb = $thumbdir.$prefix.$userfile_name;
         move_uploaded_file($userfile_tmp, $prod_img);
         chmod ($prod_img, octdec($mode));
         $sizes = getimagesize($prod_img);
         $aspect_ratio = $sizes[1]/$sizes[0]; 
         if ($sizes[0] <= $size)
         {
             $new_width = $sizes[0];
             $new_height = $sizes[1];
         }else{
             $new_height = $size;
             $new_width = abs($new_height/$aspect_ratio);
         }
         $destimg=ImageCreateTrueColor($new_width,$new_height)
             or die('Problem In Creating image');
         $srcimg=ImageCreateFromJPEG($prod_img)
             or die('Problem In opening Source Image');
         if(function_exists('imagecopyresampled'))
         {
             imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
             or die('Problem In resizing');
         }else{
             Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
             or die('Problem In resizing');
         }
         ImageJPEG($destimg,$prod_img_thumb,90)
             or die('Problem In saving');
         imagedestroy($destimg);

     }
$con = mysql_connect("localhost","*****","*****");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("*****", $con);

mysql_query("INSERT INTO ***** (name, thumburl, fullurl, idnum)
VALUES ('".$picname."', '".$prod_img_thumb."', '".$prod_img."', '0')");

mysql_close($con);

     echo '
     <a href="'.$prod_img.'">
         <img src="'.$prod_img_thumb.'" width="'.$new_width.'" heigt="'.$new_height.'"><br />
     </a>
     <a href="./" target="_self">Upload Another</a>';
 }else{
     echo '
     <form method="POST" action="index.php" enctype="multipart/form-data">
     <input type="file" name="image" /><br />
     <input type="text" name="picname" /><br />
     <input type="Submit" name="Submit" value="Submit" />
     </form>';
 }
?>

Open in new window

John GrosshansDirector of TechnologyAsked:
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.

KalpanCommented:
you could use the following function for the particular width and height and other params

$imgSrc = uploaded file info

$thumbnail_width = 280;
$thumbnail_height= 200;

$Thumb = upload path

Hope that helps




function ResizImages($filetype,$imgSrc,$thumbnail_width,$thumbnail_height,$Thumb) { //$imgSrc is a FILE - Returns an image resource.
            //getting the image dimensions
            list($width_orig, $height_orig) = getimagesize($imgSrc);
            //$myImage = imagecreatefromjpeg($imgSrc);
            $image_type = strrchr($filetype, ".");
            switch($image_type) {
              case '.jpg':
                $myImage = imagecreatefromjpeg($imgSrc);
                break;
             case '.jpeg':
                $myImage = imagecreatefromjpeg($imgSrc);
                break;
             case '.JPG':
                $myImage = imagecreatefromjpeg($imgSrc);
                break;
             case '.JPEG':
                $myImage = imagecreatefromjpeg($imgSrc);
                break;
             case '.png':
                $myImage = imagecreatefrompng($imgSrc);
                break;
             case '.PNG':
                $myImage = imagecreatefrompng($imgSrc);
                break;
             case '.gif':
                $myImage = imagecreatefromgif($imgSrc);
                break;
             case '.GIF':
                $myImage = imagecreatefrompng($imgSrc);
                break;
             case '.bmp':
                $myImage = BMP::imagecreatefrombmp($imgSrc);
                break;
             case '.BMP':
                $myImage = BMP::imagecreatefrombmp($imgSrc);
                break;
             default:
                    //echo "Error Invalid Image Type <a href='javascript:history.go(-1);'>'.'&lt;&lt Go Back</a>");
                    die('<b>'.$filetype.' is an invalid file type!</b><br/>'.
                            '<a href="javascript:history.go(-1);">'.
                            '&lt;&lt Go Back</a>');
                break;
             }

             
            $ratio_orig = $width_orig/$height_orig;

            if ($thumbnail_width/$thumbnail_height > $ratio_orig) {

               $new_height = $thumbnail_width/$ratio_orig;

               $new_width = $thumbnail_width;

            } else {

               $new_width = $thumbnail_height*$ratio_orig;

               $new_height = $thumbnail_height;

            }

            $x_mid = $new_width/2;  //horizontal middle

            $y_mid = $new_height/2; //vertical middle

            $process = imagecreatetruecolor(round($new_width), round($new_height));

            imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);

            $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);

            imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);

            imagejpeg($thumb,$Thumb,100);

            imagedestroy($process);

            imagedestroy($myImage);
    }

Open in new window

0
Beverley PortlockCommented:
There is working code here http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_24935011.html#25924977 that you should be able to use. It works by having a tumbnail folder that you place all the thumbnails in and you link to these for the gallery. When an image is clicked or hovered over you show the original image.

0
Ray PaseurCommented:
You can copy this image to use for test data.
http://www.laprbass.com/RAY_temp_600x374.jpg

You can see the script in action on my server here:
http://www.laprbass.com/RAY_resize_and_crop.php

Some of the outputs are here:
http://www.laprbass.com/RAY_temp_100x100.jpg
http://www.laprbass.com/RAY_temp_200x100.jpg
http://www.laprbass.com/RAY_temp_200x300.jpg

HTH, ~Ray
<?php // RAY_resize_and_crop.php
error_reporting(E_ALL);

// RESIZE AN IMAGE PROPORTIONALLY AND CROP CENTERED

function resize_and_crop($original_image_url, $thumb_image_url, $thumb_w, $thumb_h, $quality=75)
{
    // ACQUIRE THE ORIGINAL IMAGE: http://us3.php.net/manual/en/function.imagecreatefromjpeg.php
    $original = imagecreatefromjpeg($original_image_url);
    if (!$original) return FALSE;

    // GET ORIGINAL IMAGE DIMENSIONS
    list($original_w, $original_h) = getimagesize($original_image_url);

    // RESIZE IMAGE AND PRESERVE PROPORTIONS KEEPING AS MUCH OF THE IMAGE AS POSSIBLE
    $thumb_w_resize = $thumb_w;
    $thumb_h_resize = $thumb_h;
    if ($original_w > $original_h)
    {
        $thumb_h_ratio  = $thumb_h / $original_h;
        $thumb_w_resize = (int)round($original_w * $thumb_h_ratio);
    }
    else
    {
        $thumb_w_ratio  = $thumb_w / $original_w;
        $thumb_h_resize = (int)round($original_h * $thumb_w_ratio);
    }
    if ($thumb_w_resize < $thumb_w)
    {
        $thumb_h_ratio  = $thumb_w / $thumb_w_resize;
        $thumb_h_resize = (int)round($thumb_h * $thumb_h_ratio);
        $thumb_w_resize = $thumb_w;
    }

    // CREATE THE PROPORTIONAL IMAGE RESOURCE
    $thumb = imagecreatetruecolor($thumb_w_resize, $thumb_h_resize);
    if (!imagecopyresampled($thumb, $original, 0,0,0,0, $thumb_w_resize, $thumb_h_resize, $original_w, $original_h)) return FALSE;

    // ACTIVATE THIS TO STORE THE INTERMEDIATE IMAGE
    // imagejpeg($thumb, 'RAY_temp_' . $thumb_w_resize . 'x' . $thumb_h_resize . '.jpg', 100);

    // CREATE THE CENTERED CROPPED IMAGE TO THE SPECIFIED DIMENSIONS
    $final = imagecreatetruecolor($thumb_w, $thumb_h);

    $thumb_w_offset = 0;
    $thumb_h_offset = 0;
    if ($thumb_w < $thumb_w_resize)
    {
        $thumb_w_offset = (int)round(($thumb_w_resize - $thumb_w) / 2);
    }
    else
    {
        $thumb_h_offset = (int)round(($thumb_h_resize - $thumb_h) / 2);
    }

    if (!imagecopy($final, $thumb, 0,0, $thumb_w_offset, $thumb_h_offset, $thumb_w_resize, $thumb_h_resize)) return FALSE;

    // STORE THE FINAL IMAGE - WILL OVERWRITE $thumb_image_url
    if (!imagejpeg($final, $thumb_image_url, $quality)) return FALSE;
    return TRUE;
}

// USE CASE
resize_and_crop('RAY_temp_600x374.jpg', 'RAY_temp_100x100.jpg', 100, 100);
resize_and_crop('RAY_temp_600x374.jpg', 'RAY_temp_200x100.jpg', 200, 100);
resize_and_crop('RAY_temp_600x374.jpg', 'RAY_temp_200x300.jpg', 200, 300);

Open in new window

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
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
PHP

From novice to tech pro — start learning today.