PHP: Crop image function


See our logo
Free online tutorials

Step 1: detect filetype (gif, jpeg, png)

use function getimagesize

result:

array(6) {
[0]=>
int(300)
[1]=>
int(107)
[2]=>
int(3)
[3]=>
string(24) “width=”300″ height=”107″”
[“bits”]=>
int(8)
[“mime”]=>
string(9) “image/png”
}

Note: Returns a array with 6 elements.
The 0 index is the width of the image in pixels.
The 1 index is the height of the image in pixels.
The 2 index is a flag for the image type:

1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel), 8 = TIFF(motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM.

The 3 index contains ‘width=”xxx” height=”yyy”‘

Step 2:

GD support 3 functions below:

imagecreatefromgif
imagecreatefromjpeg
imagecreatefrompng

<?php
set_time_limit(0);

function createblankpng($w, $h)
{
    $im = imagecreatetruecolor($w, $h);
    imagesavealpha($im, true);
    $transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
    imagefill($im, 0, 0, $transparent);
    return $im;
}

$file_loc = 'http://tutorialspots.com/wp-content/uploads/2012/08/logo1.png';
$info = getimagesize($file_loc);

switch ($info[2]) {
    case 1: //gif image
        $image = imagecreatefromgif($file_loc);
        break;

    case 2: //jpeg  image
        $image = imagecreatefromjpeg($file_loc);
        break;

    case 3: //png  image
        $image = imagecreatefrompng($file_loc);
        break;

    default:
        trigger_error('Support GIF JPEG PNG only', E_USER_ERROR);
        break;
}

$crop = createblankpng(270, 60);
imagecopy($crop, $image, 0, 0, 8, 26, 270, 60);

header("Content-Type: image/png");

imagepng($crop);
imagedestroy($image);
imagedestroy($crop);
?>

We get result:

Online demo

Next: PHP: Crop image function (part 2)

Leave a Reply