Search code examples
phpgdjcrop

imagecopyresampled issues...dimensions not quite right


I'm having an issue cropping an image and thought perhaps someone out there could help. Basically, I am using jCrop to crop an image to a specified x, y, width, height and am using the following on the back-end to process the image:

<?php
    $image = imagecreatefromjpeg(DOC_ROOT . '/' . $db_image->source);   
    list($image_width, $image_height) = getimagesize(DOC_ROOT . '/' . $db_image->source);
    $cf = $data->cropping_factor;
    $new_image = imagecreatetruecolor($cf * $data->crop_data['w'], $cf * $data->crop_data['h']);
    imagecopyresampled(
        $new_image, 
        $image, 
        0, //Destination x coordinate
        0, //Destination x coordinate
        intval($cf * $data->crop_data['x']), //Source X coordinate
        intval($cf * $data->crop_data['y']), //Source Y coordinate
        intval($cf * $data->crop_data['w']), //Destination W
        intval($cf * $data->crop_data['h']), //Destination H
        $image_width, //Original W
        $image_height //Original H
    );
    imagejpeg($new_image, DOC_ROOT . '/' . $db_image->source, 100);
?>

Basically, this code leaves me with:

Array
(
    [0] => Resource id #33 //New Image
    [1] => Resource id #31 //Source Image
    [2] => 0 //Destination X
    [3] => 0 //Destination Y
    [4] => 114 //Source X
    [5] => 407 //Source Y
    [6] => 786 //New Width
    [7] => 293 //New Height
    [8] => 900 //Original Width
    [9] => 700 //Original Height
)

The original image can be found here: http://cl.ly/image/3Y0l1a2h3U2S. The resized image can be found here: http://cl.ly/image/0Q3J2c2q0N1j.

Thanks for the help.


Solution

  • After further examination, it appeared that the image was distorted (the bars were slanted at different degrees). With that information, I thought the the scale must be off. Therefore, I changed the code to the following:

    <?php
        imagecopyresampled(
            $new_image, 
           $image, 
           0, //Destination x coordinate
           0, //Destination x coordinate
           intval($cf * $data->crop_data['x']), //Source X coordinate
           intval($cf * $data->crop_data['y']), //Source Y coordinate
           $image_width, //Original W
           $image_height //Original H
           $image_width, //Original W
           $image_height //Original H
        );
    ?>
    

    This fixed the issue by not scaling the new destination image's coordinates.