Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

resize image with php

Posted on 2009-05-12
3
845 Views
Last Modified: 2012-06-27
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

0
Comment
Question by:jimfrith
3 Comments
 
LVL 2

Expert Comment

by:lavinpj1
ID: 24373410
Look at using imagemagick over GD - it is much more powerful.

Phil
0
 
LVL 18

Accepted Solution

by:
Hube02 earned 500 total points
ID: 24373414
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
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24378069
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

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

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

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

829 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