imagefilledrectangle() function in PHP

The imagefilledrectangle() function in PHP draws a filled rectangle on an image resource. This function is part of the GD extension and is commonly used for creating graphics, overlays, and visual elements programmatically.

Syntax

imagefilledrectangle($image, $x1, $y1, $x2, $y2, $color)

Parameters

  • $image − An image resource created by functions like imagecreatetruecolor().

  • $x1 − x-coordinate of the first corner (top-left).

  • $y1 − y-coordinate of the first corner (top-left).

  • $x2 − x-coordinate of the opposite corner (bottom-right).

  • $y2 − y-coordinate of the opposite corner (bottom-right).

  • $color − The fill color created with imagecolorallocate().

Return Value

Returns TRUE on success or FALSE on failure.

Example

Here's how to create a filled rectangle on an image canvas ?

<?php
    // Create a 500x300 image
    $img = imagecreatetruecolor(500, 300);
    
    // Set white background
    $white = imagecolorallocate($img, 255, 255, 255);
    imagefill($img, 0, 0, $white);
    
    // Create teal color for rectangle
    $teal = imagecolorallocate($img, 0, 128, 128);
    
    // Draw filled rectangle from (30,30) to (470,270)
    imagefilledrectangle($img, 30, 30, 470, 270, $teal);
    
    // Output as PNG
    header("Content-type: image/png");
    imagepng($img);
    imagedestroy($img);
?>

Key Points

  • Coordinates are specified as two opposite corners of the rectangle

  • The rectangle includes both the starting and ending coordinates

  • Colors must be allocated using imagecolorallocate() before use

  • Always call imagedestroy() to free memory after image processing

Conclusion

The imagefilledrectangle() function provides an efficient way to draw solid rectangles on image resources. It's essential for creating backgrounds, borders, and geometric shapes in PHP-generated graphics.

Updated on: 2026-03-15T07:47:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements