ARTICLE AD BOX
I'm working on a WinForms application in C# where I process a bitmap pixel by pixel and remap its colors based on brightness.
What it does is:
Lets the user to select 5 colors in colorpanel
Finds the brightness of each individual pixel
Replace the pixel with one of the selected colors depending on brightness ranges
The code looks like this:
private void fiveColorsToolStripMenuItem_Click(object sender, EventArgs e) { Color currentPixel; int brightness; Bitmap sourceBitmap = btm.Bitmapa; Bitmap resultBitmap = new Bitmap(sourceBitmap); Color chosenColor = colorDialog.Color; Color[] colorArray = new Color[5]; // array with five colors for (int index = 0; index < 5; index++) { if (colorDialog.ShowDialog() == DialogResult.OK) { colorArray[index] = colorDialog.Color; } } for (int x = 0; x < sourceBitmap.Width; x++) { for (int y = 0; y < sourceBitmap.Height; y++) { currentPixel = sourceBitmap.GetPixel(x, y); brightness = btm.brightness(currentPixel); Color newColor = new Color(); if (brightness < 50) { newColor = Color.FromArgb(Convert.ToInt32(colorArray[4].R), Convert.ToInt32(colorArray[4].G), Convert.ToInt32(colorArray[4].B)); } else if (brightness >= 50 && brightness < 100) { newColor = Color.FromArgb(Convert.ToInt32(colorArray[3].R), Convert.ToInt32(colorArray[3].G), Convert.ToInt32(colorArray[3].B)); } else if (brightness >= 100 && brightness < 150) { newColor = Color.FromArgb(Convert.ToInt32(colorArray[2].R), Convert.ToInt32(colorArray[2].G), Convert.ToInt32(colorArray[2].B)); } else if (brightness >= 150 && brightness < 200) { newColor = Color.FromArgb(Convert.ToInt32(colorArray[1].R), Convert.ToInt32(colorArray[1].G), Convert.ToInt32(colorArray[1].B)); } else if (brightness >= 200) { newColor = Color.FromArgb(colorArray[0].R, colorArray[0].G, colorArray[0].B); } resultBitmap.SetPixel(x, y, newColor); } } btm.Bitmapa = resultBitmap; //Bitmapa is an atribute btm.zobrazitBitovouMapu(new Point(0, 0), Form.ActiveForm); }The code works, but I have a two questions:
Is there a better way to do the if/else if part? It seems like a lot of code to do this task.
Is using Get/SetPixel optimal, or should I use something better?
