How to get the clipping rectangle using imagegetclip() function in PHP?

The imagegetclip() function is a built-in PHP function used to retrieve the current clipping rectangle of an image. The clipping rectangle defines the area within which pixels can be drawn − any drawing operations outside this area will be ignored.

Syntax

array imagegetclip(resource $image)

Parameters

The imagegetclip() function takes only one parameter:

$image − An image resource created by image creation functions like imagecreatetruecolor() or imagecreatefrompng().

Return Value

Returns an indexed array containing four integers representing the clipping rectangle coordinates:

  • [0] − x-coordinate of upper-left corner
  • [1] − y-coordinate of upper-left corner
  • [2] − x-coordinate of lower-right corner
  • [3] − y-coordinate of lower-right corner

Example 1: Getting Default Clipping Rectangle

When an image is created, the default clipping rectangle covers the entire image ?

<?php
    $img = imagecreate(200, 200);
    
    // Get the default clipping rectangle
    $clip = imagegetclip($img);
    print_r($clip);
    
    // Clean up memory
    imagedestroy($img);
?>
Array
(
    [0] => 0
    [1] => 0
    [2] => 200
    [3] => 200
)

Example 2: Custom Clipping Rectangle

You can set a custom clipping area using imagesetclip() and then retrieve it ?

<?php
    $img = imagecreate(200, 200);
    
    // Set a custom clipping rectangle (x1, y1, x2, y2)
    imagesetclip($img, 20, 20, 90, 90);
    
    // Get the current clipping rectangle
    $clip = imagegetclip($img);
    print_r($clip);
    
    imagedestroy($img);
?>
Array
(
    [0] => 20
    [1] => 20
    [2] => 90
    [3] => 90
)

Practical Use Case

This function is useful when you need to determine the current drawing boundaries, especially in image editing applications ?

<?php
    $img = imagecreatetruecolor(300, 200);
    
    // Set clipping to create a border effect
    imagesetclip($img, 10, 10, 290, 190);
    
    $clip = imagegetclip($img);
    echo "Clipping area: ";
    echo "Top-left ({$clip[0]}, {$clip[1]}) to ";
    echo "Bottom-right ({$clip[2]}, {$clip[3]})";
    
    imagedestroy($img);
?>
Clipping area: Top-left (10, 10) to Bottom-right (290, 190)

Conclusion

The imagegetclip() function provides essential information about the current drawing boundaries in image manipulation. Use it alongside imagesetclip() to control and verify clipping regions for precise image editing operations.

Updated on: 2026-03-15T09:48:12+05:30

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements