Introduction
Fill with color in photo editors change specific area color with selected color. This job may be needed in other image processing tasks. The current tip shows one simple way to implement fill with color.
Background
Steps:
- Select and load source image
- Select position and get its color in image
Pictures have specific size that is divided in width and height, that each pixel has a certain position X and Y, for easy pixel selection picture size after load time must be equal to the actual size (for scale, avoid any easy pixel selection) - Select new color
- Fill Color
Changing pixels color continue until color has been changed, on the other hand, region borders reach when it finds pixels with different color. The algorithm that is used in this approach is:
- Change Color of first selected pixel and add that position to queue
- While queue is not empty, do the following:
- Dequeue one position
- Find the neighborhood pixels in left, right, top, down direction positions of the current position
- Check the color of that position pixel if same with the first color:
- Change pixel color to fill color
- Add to queue
- Save image
Using the Code
I implemented the Fill
method:
private void btnFill_Click(object sender, EventArgs e)
{
if (SColor == true && isload == true)
{
Queue q = new Queue();
ArrayList PreList = new ArrayList();
int x1 = int.Parse(txtX.Text);
int y1 = int.Parse(txtY.Text);
Point p = new Point(x1, y1);
q.Enqueue(p);
img.SetPixel(x1, y1, pic3.BackColor);
while (q.Count > 0)
{
p = (Point)q.Dequeue();
x1 = p.X;
y1 = p.Y;
for (int i = 1; i <= 4; i++)
{
int x2 = x1;
int y2 = y1;
switch (i)
{
case 1:
x2--;
break;
case 2:
x2++;
break;
case 3:
y2++;
break;
case 4:
y2--;
break;
}
if (x2 < img.Width && x2 >= 0 && y2 < img.Height && y2 >= 0)
{
if (img.GetPixel(x2, y2) == pic2.BackColor)
{
img.SetPixel(x2, y2, pic3.BackColor);
Point p2 = new Point(x2, y2);
q.Enqueue(p2);
}
}
}
}
pic1.Image = img;
}
}
Input image (that isn't original photos, because of reducing web page size):
Output image after two fills:
Form view:
Points of Interest
Fill any type of image in color range region.
History
- Implemented in April 2013