Cropping image in PHP

You could use imagecopy to crop a required part of an image. The command goes like this:

imagecopy  ( 
    resource $dst_im - the image object ,
    resource $src_im - destination image ,
    int $dst_x - x coordinate in the destination image (use 0) , 
    int $dst_y - y coordinate in the destination image (use 0) , 
    int $src_x - x coordinate in the source image you want to crop , 
    int $src_y - y coordinate in the source image you want to crop , 
    int $src_w - crop width ,
    int $src_h - crop height 
)

Code from PHP.net – a 80×40 px image is cropped from a source image

<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);

// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

Leave a Comment