resize image with php

I'm trying to size and crop an image with php.

I need to size the image as close as possible to the dimensions and then crop if necessary the center of the resized image.

the code I'm using works but when it crops the image it it crops off the right side of the image instead of croping both the left and right proportionately.

how can I make the image crop equally from both sides?
<?php
// Set our crop dimensions.
$max_width = 151;
$max_height = 113;
// Get dimensions of existing image
$size = getimagesize('../gallery/' . $_SESSION['filename1'] . ".jpg");
// Prepare canvas
 
// Prepare image resizing and crop -- Center crop location
  $ratio1 = $size[0] / 151;
 $ratio2 = $size[1] / 113;
 
 if ($ratio1 < $ratio2)
                    {
                           // set the width to the maximum possible
                              $new_width = $max_width;
                              // change the height in proportion of the other
                              // adjustment
                              $new_height = ($max_width/$size[0]) * $size[1];
                    }
                    else
                    {
                              // set the height to the maximum possible
                              $new_height = $max_height;
                              /// change the width in proportion of the other
                              // adjustment
                              $new_width = ($max_height/$size[1]) * $size[0];
                    }
$canvas = imagecreatetruecolor(151,113);
$piece = imagecreatefromjpeg('../gallery/' . $_SESSION['filename1'] . ".jpg");
//$newwidth = $dimensions[0] / 2;
//$newheight = $dimensions[1] / 2;
$cropLeft = ($new_width/2) - ($max_width/2);
$cropHeight = ($new_height/2) - ($max_height/2);
// Generate the cropped image
imagecopyresampled($canvas, $piece, 0,0, 0, 0, $new_width, $new_height, $size[0],  $size[1]);
// Write image or fail
if (imagejpeg($canvas,'../gallery/'. $timestamp ."_sm.jpg",100)) {
} else {
echo 'Image crop failed';
}
// Clean-up
 
imagedestroy($canvas);
imagedestroy($piece);
?>

Open in new window

jimfrithAsked:
Who is Participating?
 
Hube02Connect With a Mentor Commented:
I think you are calculating the starting point in the source image correctly, but you are not using the values in imagecopyresampled() function. See my altered code snippet below.

$cropLeft = ($new_width/2) - ($max_width/2);
$cropHeight = ($new_height/2) - ($max_height/2);
// Generate the cropped image
imagecopyresampled($canvas, $piece, 0, 0, $cropLeft, $cropHeight, $new_width, $new_height, $size[0],  $size[1]);

Open in new window

0
 
lavinpj1Commented:
Look at using imagemagick over GD - it is much more powerful.

Phil
0
 
Ray PaseurCommented:
Have a look at the function near line 105 in this code.  It may prove helpful.

Best, ~Ray
<?php // RAY_photo_directory.php
error_reporting(E_ALL);
 
// ALLOWABLE WIDTH AND HEIGHT
DEFINE('W', 360);
DEFINE('H', 360);
 
// THUMBNAIL PREFIX
DEFINE('T', "tn_");
 
// GET THE NAMES OF ALL THE FILES
$dir = scandir(getcwd());
 
// WINNOW THE CHAFF
foreach ($dir as $ptr => $jpg)
{
    if (!eregi(".jpg$", $jpg))
    {
        unset($dir[$ptr]);
    }
}
 
// MAKE THUMBNAILS
$prefix_regex = '^' . T;
foreach ($dir as $ptr => $jpg)
{
// IF THIS IS A THUMBNAIL, SKIP IT
    if (eregi("$prefix_regex", $jpg))
    {
        unset ($dir[$ptr]);
        continue;
    }
 
// IF WE ALREADY HAVE A THUMBNAIL
    $thumb = T . $jpg;
    if (!in_array($thumb, $dir))
    {
        $imageblob = create_right_size_image($jpg);
        imagejpeg($imageblob, $thumb);
    }
}
 
// WE HAVE ADDED TO THE DIRECTORY - REGET THE NAMES OF ALL THE FILES
$dir = scandir(getcwd());
 
// WINNOW THE CHAFF - KEEP ONLY THE ORIGINAL JPG FILE NAMES
$prefix_regex = '^' . T;
foreach ($dir as $ptr => $jpg)
{
    if ( !eregi(".jpg$", $jpg) || eregi("$prefix_regex", $jpg) )
    {
        unset($dir[$ptr]);
    }
}
 
// DISPLAY THE THUMBNAIL LINKS
foreach ($dir as $ptr => $jpg)
{
    $thumb = T . $jpg;
    echo "<br clear=\"all\" /><a href=\"$jpg\"><img src=\"$thumb\"></a>\n";
}
 
// DONE
die();
 
 
 
 
// LOCAL FUNCTIONS
 
// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{
 
// IS GD INSTALLED AT ALL?
   if (!function_exists("gd_info"))
   {
      if ($display) echo "<br/>GD NOT INSTALLED\n";
      return FALSE;
   }
 
// IF GD IS INSTALLED GET DETAILS
   $gd = gd_info();
 
// IF DISPLAY IS REQUESTED, PRINT DETAILS
   if ($display)
   {
      echo "<br/>GD DETAILS:\n";
      foreach ($gd as $key => $value)
      {
         if ($value === TRUE)  $value = 'YES';
         if ($value === FALSE) $value = 'NO';
         echo "<br/>$key = $value \n";
      }
   }
 
// RETURN THE VERSION NUMBER
   $gd_version = ereg_replace('[^0-9\.]', '', $gd["GD Version"]);;
   return $gd_version;
}
 
 
// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE
function create_right_size_image($image, $width=W, $height=H)
{
// IS GD HERE?
   $gdv = get_gd_info();
   if (!$gdv) return FALSE;
 
// GET AN IMAGE THING
   $source = imagecreatefromjpeg("$image");
 
// GET THE X AND Y DIMENSIONS
   $imageX = imagesx($source);
   $imageY = imagesy($source);
 
// IF NO RESIZING IS NEEDED
   if ( ($imageX <= $width) && ($imageY <= $height) )
   {
      return $source;
   }
 
// IF THE WIDTH IS TOO GREAT - MUST RESIZE
   if ($imageX > $width)
   {
      $tnailX = $width;
      $tnailY = (int) (($tnailX * $imageY) / $imageX );
   }
 
// IF THE HEIGHT IS TOO GREAT - MUST RESIZE
   if ($imageY > $height)
   {
      $tnailY = $height;
      $tnailX = (int) (($tnailY * $imageX) / $imageY );
   }
 
// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
   if ($gdv >= 2)
   {
// IF GD IS AT LEVEL 2 OR ABOVE
      $target = imagecreatetruecolor($tnailX, $tnailY);
      imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   } else
   {
// IF GD IS AT A LOWER REVISION LEVEL
      $target = imagecreate($tnailX, $tnailY);
      imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   }
   return $target ;
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.