Flood fill to specific color in PHP using imagefilltoborder() (GD) function.


imagefilltoborder() is an inbuilt function in PHP that is used to perform flood fill with a specific color, whose border color is defined by the border. The starting point for the fill is (x,y) or top left is (0, 0) and the region is filled with the color.

Syntax

bool imagefilltoborder(resource $image, int $x, int $y, int $border, int $color)

Parameters

imagefilltoborder() takes five different parameters: $image, $x, $y, $border, and $color.

  • $image − It is the image resource.

  • $x − Specifies the x-coordinate of start.

  • $y − Specifies the y- coordinate of start.

  • $border − Specifies the border color.

  • $color − Specifies the color.

Return Values

It returns True on success and False on failure.

Example 1

<?php
   // Load the GIF image from local drive folder.
   $img = imagecreatefromgif('C:\xampp\htdocs\Images\img39.gif');

   // Create the image colors
   $borderColor = imagecolorallocate($img, 0, 200, 0);
   $fillColor = imagecolorallocate($img, 122, 122, 122);

   // Add fill to border
   imagefilltoborder($img, 0, 0, $borderColor, $fillColor);

   // Show the output image
   header('Content-type: image/gif');
   imagepng($img);
?>

Output

Gif image before using the imagefilltoborder() function in PHP.

Gif image after using the imagefilltoborder() function in PHP.

Example 2: Fill an ellipse with a color

<?php
   // Created the image, set the background to gray color
   $img = imagecreatetruecolor(700, 500);
   imagefilledrectangle($img, 0, 0, 500, 500,imagecolorallocate($img, 122, 122, 122));

   // Draw an ellipse to fill with a black border.
   imageellipse($img, 300, 300, 300, 300, imagecolorallocate($img, 0, 0, 0));

   // Set the border and fill using the blue colors
   $border = imagecolorallocate($img, 0, 0, 0);
   $fill = imagecolorallocate($img, 0, 0, 255);

   // Fill the selection
   imagefilltoborder($img, 300, 300, $border, $fill);

   // show the output image and free memory
   header('Content-type: image/gif');
   imagepng($img);
   imagedestroy($img);
?>

Output

Updated on: 09-Aug-2021

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements