phpimageimagemagickgd

php remove pixels border around an image


I use the following code to display a remote image and cache a local version of it.

Now i need to find a way to remove 10 pixels all around the image because there's a border that needs to be removed before the image is displayed/cached.

How can i use php to remove 10 pixels on top, bottom, right and left of the image ?

header('Content-type: image/png');

$path = ".......";
$CACHE_FILE_PATH = "images_tshirts/mini_t/".$a.".png";

if(file_exists($CACHE_FILE_PATH)) {
    echo @file_get_contents($CACHE_FILE_PATH);
} 
else {
    $image = imagecreatefromstring(file_get_contents($path));
    // Send the image
    imagepng($image, $CACHE_FILE_PATH);
    echo @file_get_contents($CACHE_FILE_PATH);
    exit();
}
?>

Solution

  • imagecrop — Crop an image using the given coordinates and size, x, y, width and height

    http://php.net/manual/en/function.imagecrop.php

    Edit: example from the linked page, as requested. Modify to account for 10px border:

    <?php
    // Create a blank image and add some text
    $ini_filename = 'test.JPG';
    $im = imagecreatefromjpeg($ini_filename );
    
    $ini_x_size = getimagesize($ini_filename )[0];
    $ini_y_size = getimagesize($ini_filename )[1];
    
    //the minimum of xlength and ylength to crop.
    $crop_measure = min($ini_x_size, $ini_y_size);
    
    // Set the content type header - in this case image/jpeg
    //header('Content-Type: image/jpeg');
    
    $to_crop_array = array('x' =>0 , 'y' => 0, 'width' => $crop_measure, 'height'=> $crop_measure);
    $thumb_im = imagecrop($im, $to_crop_array);
    
    imagejpeg($thumb_im, 'thumb.jpeg', 100);
    ?>