Splitting the color circle into sections - c#

How I can programmatically split the color circle into sections, and how I can get all RGB color in this sections ?
I want fce which returns me the color section by input parament in RGB color.
int getColorSection(RGB color);

I don't know if i understood correctly the question, but i think you are asking if a color is more green, more blue or blue red?
This will give you informations on in what section (Red, Green or Blue) it is.
For doing that, without keeping in account human perception of colors, you can do:
public enum ColorSection
{
Red,
Green,
Blue
}
public ColorSection GetColorSection(int rgb)
{
int r = rgb & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb >> 16) & 0xFF;
return (r > g && r > b) ? ColorSection.Red : ((g > b) ? ColorSection.Green : ColorSection.Blue);
}
Of course this don't work very well if you have colors with two equal values, if you have red = green, it returns red.
If you have white it returns red, if you have black, it returns blue.
If you need something more fancy, probably as you are asking, then you need to use neirest neighbour approximation and polar coordinates.
You can compute the angle using, as pointed out, the Hue.
From the angle then you can just convert it to an integer.
To compute the hue:
public static double GetHue(int rgb)
{
double result = 0.0;
int r = rgb & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb >> 16) & 0xFF;
if (r != g && g != b)
{
double red = r / 255.0;
double green = g / 255.0;
double blue = b / 255.0;
double max = Math.Max(Math.Max(red, green), blue);
double min = Math.Min(Math.Min(red, green), blue);
double delta = max - min;
if (delta != 0)
{
if (red == max)
result = (green - blue) / delta;
else if (green == max)
result = 2 + ((blue - red) / delta);
else if (blue == max)
result = 4 + ((red - green) / delta);
result *= 60.0;
if (result < 0)
result += 360.0;
}
}
return result;
}
It returns the angle, in degrees, from 0 to 360, of where are you in the color wheel.
You can compute than the section using neirest neighbour.
For example:
const int NumberOfSections = 10;
int section = (int)(GetHue() * NumberOfSections / 360.0);
Your wheel however seems rotated in respect to the C# color wheel.
You probably need to substract a constant angle that is the exact difference.
If i'm not wrong, the difference is 180°.
public static double GetMyHue(int rgb)
{
return (GetHue(rgb) + 180.0) % 360.0;
}

Use the HSL color space. The H is the hue, the angle of the color on the color circle. You can get it directly from the System.Drawing.Color.GetHue() method.

Related

Red Pass Filter for Image Processing in C#

I am trying to code a Red Pass filer in C#. I might not be using the correct name for this, but I want to convert all the non-red pixel to black (0,0,0).
So, like how a high pass filter sets all frequencies below a giving setpoint to 0. I want to set all the non-red pixel to (0,0,0) aka Black.
My problem is that I am using images from a camera, so the red pixels are not (255,0,0) plus because of Light and shades on the object I am taking a picture of some of the red pixels are darker than others. Meaning this [Red Color] (https://i.stack.imgur.com/Hc42q.png) and this Red Color are on the same object in the image.
This is what I have Tried so for:
public bool IsRed(RGB color)
{
// The pixel is a shade of red if the red value is greater than the green and blue values
return color.Red > color.Green && color.Red > color.Blue;
}
public bool IsRed2(RGB color)
{
// The pixel is a shade of red if the red value is within the range of 128 to 255.
return color.Red >= 128 && color.Red <= 255;
}
public bool IsRed3(RGB color)
{
// Convert the RGB values to HSL.
double hue, saturation, lightness;
RGBToHSL(color.Red, color.Green, color.Blue, out hue, out saturation, out lightness);
// The pixel is a shade of red if the hue is within the range of 0 to 30 degrees or 330 to 360 degrees.
return (hue >= 0 && hue <= 30) || (hue >= 330 && hue <= 360);
}
// Converts the given RGB values to HSL.
private void RGBToHSL(byte red, byte green, byte blue, out double hue, out double saturation, out double lightness)
{
// Convert the RGB values to the range 0 to 1.
double r = red / 255.0;
double g = green / 255.0;
double b = blue / 255.0;
// Calculate the maximum and minimum RGB values.
double max = Math.Max(r, Math.Max(g, b));
double min = Math.Min(r, Math.Min(g, b));
// Calculate the lightness.
lightness = (max + min) / 2;
// Calculate the saturation.
if (max == min)
{
// The color is a shade of gray.
hue = 0;
saturation = 0;
}
else
{
// The color is not a shade of gray.
double d = max - min;
saturation = lightness > 0.5 ? d / (2 - max - min) : d / (max + min);
// Calculate the hue.
if (max == r)
{
hue = (g - b) / d + (g < b ? 6 : 0);
}
else if (max == g)
{
hue = (b - r) / d + 2;
}
else
{
hue = (r - g) / d + 4;
}
hue /= 6;
}
}
Update :
This is how I am getting the RGB values from the image:
private RGB[,] ImageToRGBByteArray(Bitmap _image, int height, int width)
{
Bitmap b = new Bitmap(_image);
BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat);
/* GetBitsPerPixel just does a switch on the PixelFormat and returns the number */
BitsPerPixel = GetBitsPerPixel(bData.PixelFormat);
/*the size of the image in bytes */
int size = bData.Stride * bData.Height;
Stride = bData.Stride;
/*Allocate buffer for image*/
byte[] data = new byte[size];
RGB[,] imagematrix = new RGB[height, width];
int[,] imageData = new int[height, width];
/*This overload copies data of /size/ into /data/ from location specified (/Scan0/)*/
Marshal.Copy(bData.Scan0, data, 0, size);
int i = 0;
ModifiedHistogram = null;
ImageData = null;
ImageRGBData = null;
Dictionary<RGB, int> modifiedHistogram = new Dictionary<RGB, int>();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
RGB tempValue = new RGB(data[i], data[i + 1], data[i + 2]);
imagematrix[y, x] = tempValue;
imageData[y, x] = (int)((data[i] + data[i + 1] + data[i + 2]) / 3D);
if (!modifiedHistogram.ContainsKey(tempValue))
modifiedHistogram.Add(tempValue, 1);
else
modifiedHistogram[tempValue]++;
i += BitsPerPixel / 8;
}
}
int maxValue = 0;
string color = string.Empty;
foreach (var kvp in modifiedHistogram)
{
if (kvp.Value > maxValue)
{
maxValue = kvp.Value;
color = kvp.Key.ColorName;
}
}
ImageData = imageData;
ImageRGBData = imagematrix;
ModifiedHistogram = modifiedHistogram;
return imagematrix;
}
So
data[i] = Red
data[i+2] = Green
data[i+3] = Blue
This is my Color class
public class RGB
{
public byte Red { get; set; }
public byte Green { get; set; }
public byte Blue { get; set; }
public RGB(byte red, byte green, byte blue)
{
Red = red;
Green = green;
Blue = blue;
SetColorName();
}
public override bool Equals(object obj)
{
RGB other = obj as RGB;
return other != null && other.ColorName == this.ColorName;
}
}

C# setHue (or alternatively, convert HSL to RGB and set RGB)

C# has a very convenient getHue method, but I can't find a setHue method. Is there one?
If not, I think the best way to define a color after changing the hue would be to convert the HSL value to RGB, and then set the RGB value. I know there are formulas on the internet for doing this, but how would I best go about performing this conversion from HSL to RGB using C#?
Thank You
To set the Hue you create a new Color, maybe from a given one by using GetHue and GetSaturation. See below for the getBrightness function!
I'm using this:
Color SetHue(Color oldColor)
{
var temp = new HSV();
temp.h = oldColor.GetHue();
temp.s = oldColor.GetSaturation();
temp.v = getBrightness(oldColor);
return ColorFromHSL(temp);
}
// A common triple float struct for both HSL & HSV
// Actually this should be immutable and have a nice constructor!!
public struct HSV { public float h; public float s; public float v;}
// the Color Converter
static public Color ColorFromHSL(HSV hsl)
{
if (hsl.s == 0)
{ int L = (int)hsl.v; return Color.FromArgb(255, L, L, L); }
double min, max, h;
h = hsl.h / 360d;
max = hsl.v < 0.5d ? hsl.v * (1 + hsl.s) : (hsl.v + hsl.s) - (hsl.v * hsl.s);
min = (hsl.v * 2d) - max;
Color c = Color.FromArgb(255, (int)(255 * RGBChannelFromHue(min, max,h + 1 / 3d)),
(int)(255 * RGBChannelFromHue(min, max,h)),
(int)(255 * RGBChannelFromHue(min, max,h - 1 / 3d)));
return c;
}
static double RGBChannelFromHue(double m1, double m2, double h)
{
h = (h + 1d) % 1d;
if (h < 0) h += 1;
if (h * 6 < 1) return m1 + (m2 - m1) * 6 * h;
else if (h * 2 < 1) return m2;
else if (h * 3 < 2) return m1 + (m2 - m1) * 6 * (2d / 3d - h);
else return m1;
}
Do not use the built-in GetBrightness method! It returns the same value (0.5f) for red, magenta, cyan, blue and yellow (!). This is better:
// color brightness as perceived:
float getBrightness(Color c)
{ return (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f; }
System.Drawing.Color is a value type, which are almost always made immutable, especially in frameworks. That's why you can't setHue on it, you can only construct a new value type with fields you need.
So, if you have a function that will give you RGB values for your HSB values, you can do it like this
Color oldColor = ...;
int red, green, blue;
FromHSB(oldColor.GetHue(), oldColor.GetSaturation(), oldColor.GetBrightness(), out red, out green out blue);
Color newColor = Color.FromArgb(oldColor.A, red, green, blue);
where FromHSB looks like this
void FromHSB(float hue, float saturation, float brightness, out int red, out int green, out int blue)
{
// ...
}

C#: Create a lighter/darker color based on a system color [duplicate]

This question already has answers here:
How do I adjust the brightness of a color?
(7 answers)
Closed 1 year ago.
Duplicate
How do I adjust the brightness of a color?
How do I determine darker or lighter color variant of a given color?
Programmatically Lighten a Color
Say I have
var c = Color.Red;
Now I want to create a new Color that is lighter or darker than that color. How can I do that without too much hassle?
ControlPaint.Light .Dark .DarkDark, etc.
Color lightRed = ControlPaint.Light( Color.Red );
I recently blogged about this. The main idea is to apply a given correction factor to each of the color components. The following static method modifies the brightness of a given color with a specified correction factor and produces a darker or a lighter variant of that color:
/// <summary>
/// Creates color with corrected brightness.
/// </summary>
/// <param name="color">Color to correct.</param>
/// <param name="correctionFactor">The brightness correction factor. Must be between -1 and 1.
/// Negative values produce darker colors.</param>
/// <returns>
/// Corrected <see cref="Color"/> structure.
/// </returns>
public static Color ChangeColorBrightness(Color color, float correctionFactor)
{
float red = (float)color.R;
float green = (float)color.G;
float blue = (float)color.B;
if (correctionFactor < 0)
{
correctionFactor = 1 + correctionFactor;
red *= correctionFactor;
green *= correctionFactor;
blue *= correctionFactor;
}
else
{
red = (255 - red) * correctionFactor + red;
green = (255 - green) * correctionFactor + green;
blue = (255 - blue) * correctionFactor + blue;
}
return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
}
You can also do this using a Lerp function. There's one in XNA, but it's easy to write yourself.
See my answer to this similar question for a C# implementation.
The function lets you do this:
// make red 50% lighter:
Color.Red.Lerp( Color.White, 0.5 );
// make red 75% darker:
Color.Red.Lerp( Color.Black, 0.75 );
// make white 10% bluer:
Color.White.Lerp( Color.Blue, 0.1 );
Most of these methods do darken the color but they adjust the hue way to much so the result doesn't look very good. The best answer is to use Rich Newman's HSLColor class and adjust the luminosity.
public Color Darken(Color color, double darkenAmount) {
HSLColor hslColor = new HSLColor(color);
hslColor.Luminosity *= darkenAmount; // 0 to 1
return hslColor;
}
Taking the core method of #Pavel's answer I prepared the following two little extension methods for a more intuitive (at least for me) signature.
public static Color LightenBy(this Color color, int percent)
{
return ChangeColorBrightness(color, percent/100.0);
}
public static Color DarkenBy(this Color color, int percent)
{
return ChangeColorBrightness(color, -1 * percent / 100.0);
}
Here's some javascript code I use for lightening/darkening a given colour. You could use it as a base for an equivalent C# function
It works by calculating a distance from pure white of each of the RGB components and then adjusts this distance by the provided factor. The new distance is used to calculate the new colour. A factor of between 0 and 1 darkens, a factor higher than 1 lightens
function Darken( hexColor, factor )
{
if ( factor < 0 ) factor = 0;
var c = hexColor;
if ( c.substr(0,1) == "#" )
{
c = c.substring(1);
}
if ( c.length == 3 || c.length == 6 )
{
var i = c.length / 3;
var f; // the relative distance from white
var r = parseInt( c.substr(0, i ), 16 );
f = ( factor * r / (256-r) );
r = Math.floor((256 * f) / (f+1));
r = r.toString(16);
if ( r.length == 1 ) r = "0" + r;
var g = parseInt( c.substr(i, i), 16);
f = ( factor * g / (256-g) );
g = Math.floor((256 * f) / (f+1));
g = g.toString(16);
if ( g.length == 1 ) g = "0" + g;
var b = parseInt( c.substr( 2*i, i),16 );
f = ( factor * b / (256-b) );
b = Math.floor((256 * f) / (f+1));
b = b.toString(16);
if ( b.length == 1 ) b = "0" + b;
c = r+g+b;
}
return "#" + c;
}
You can also simply work on the RGB percentage to get it lighter or darker as you want, Here is an example for how to make a color darker x% than it is:
//_correctionfactory in percentage, e.g 50 = make it darker 50%
private Color DarkerColor(Color color, float correctionfactory = 50f)
{
const float hundredpercent = 100f;
return Color.FromArgb((int)(((float)color.R / hundredpercent) * correctionfactory),
(int)(((float)color.G / hundredpercent) * correctionfactory), (int)(((float)color.B / hundredpercent) * correctionfactory));
}
One more thing we can also reverse the process to be lighter instead, Only we getting the result of 255 - RGB and then multiply it by the percentage we want like the following example:
private Color LighterColor(Color color, float correctionfactory = 50f)
{
correctionfactory = correctionfactory / 100f;
const float rgb255 = 255f;
return Color.FromArgb((int)((float)color.R + ((rgb255 - (float)color.R) * correctionfactory)), (int)((float)color.G + ((rgb255 - (float)color.G) * correctionfactory)), (int)((float)color.B + ((rgb255 - (float)color.B) * correctionfactory))
);
}
Hope that helps.
I made a site that does this colorglower.com You can check it out to see a demo.
Here's the javascript code i used.
function lighten(color) {
// convert to decimal and change luminosity
var luminosity = 0.01
var computedColors = new Array();
var newColor = "#",
c, i, n, black = 0,
white = 255;
for (n = 0; n < 10; n++) {
for (i = 0; i < 3; i++) {
c = parseInt(color.substr(i * 2, 2), 16);
c = Math.round(Math.min(Math.max(black, c + (luminosity * white)), white)).toString(16);
newColor += ("00" + c).substr(c.length);
}
computedColors[n] = newColor;
var arrayUnique = checkIfArrayIsUnique(computedColors);
if (arrayUnique == false) {
computedColors.pop();
break;
}
computedColors[n] = newColor;
newColor = "#";
luminosity += calcPercentage();
}
return computedColors;
}
What this code does is it receives a hex color and then it outputs 10 lightest color versions of it and puts in in the array. You can change the luminosity to whatever you like to adjust the shade percentage. To darken the colors you just need to change:
luminosity -= calcPercentage();
Using HSI converter library(search google). And then, adjust I channel for lighter/darker color.
I changed Pavel Vladov function to modify even RGB component, to get shades on any combination of R/G/B directions:
Public Function ChangeColorShades(color As Color, correctionFactor As Single, bR As Boolean, bG As Boolean, bB As Boolean) As Color
Dim red As Single = CSng(color.R)
Dim green As Single = CSng(color.G)
Dim blue As Single = CSng(color.B)
If (correctionFactor < 0) Then
correctionFactor = 1 + correctionFactor
If bR Then
red *= correctionFactor
End If
If bG Then
green *= correctionFactor
End If
If bB Then
blue *= correctionFactor
End If
Else
If bR Then
red = (255 - red) * correctionFactor + red
End If
If bG Then
green = (255 - green) * correctionFactor + green
End If
If bB Then
blue = (255 - blue) * correctionFactor + blue
End If
End If
Return color.FromArgb(color.A, CInt(red), CInt(green), CInt(blue))
End Function

How to Convert RGB Color to HSV?

How can I convert a RGB Color to HSV using C#?
I've searched for a fast method without using any external library.
Note that Color.GetSaturation() and Color.GetBrightness() return HSL values, not HSV.
The following code demonstrates the difference.
Color original = Color.FromArgb(50, 120, 200);
// original = {Name=ff3278c8, ARGB=(255, 50, 120, 200)}
double hue;
double saturation;
double value;
ColorToHSV(original, out hue, out saturation, out value);
// hue = 212.0
// saturation = 0.75
// value = 0.78431372549019607
Color copy = ColorFromHSV(hue, saturation, value);
// copy = {Name=ff3278c8, ARGB=(255, 50, 120, 200)}
// Compare that to the HSL values that the .NET framework provides:
original.GetHue(); // 212.0
original.GetSaturation(); // 0.6
original.GetBrightness(); // 0.490196079
The following C# code is what you want. It converts between RGB and HSV using the algorithms described on Wikipedia. The ranges are 0 - 360 for hue, and 0 - 1 for saturation or value.
public static void ColorToHSV(Color color, out double hue, out double saturation, out double value)
{
int max = Math.Max(color.R, Math.Max(color.G, color.B));
int min = Math.Min(color.R, Math.Min(color.G, color.B));
hue = color.GetHue();
saturation = (max == 0) ? 0 : 1d - (1d * min / max);
value = max / 255d;
}
public static Color ColorFromHSV(double hue, double saturation, double value)
{
int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;
double f = hue / 60 - Math.Floor(hue / 60);
value = value * 255;
int v = Convert.ToInt32(value);
int p = Convert.ToInt32(value * (1 - saturation));
int q = Convert.ToInt32(value * (1 - f * saturation));
int t = Convert.ToInt32(value * (1 - (1 - f) * saturation));
if (hi == 0)
return Color.FromArgb(255, v, t, p);
else if (hi == 1)
return Color.FromArgb(255, q, v, p);
else if (hi == 2)
return Color.FromArgb(255, p, v, t);
else if (hi == 3)
return Color.FromArgb(255, p, q, v);
else if (hi == 4)
return Color.FromArgb(255, t, p, v);
else
return Color.FromArgb(255, v, p, q);
}
Have you considered simply using System.Drawing namespace? For example:
System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);
float hue = color.GetHue();
float saturation = color.GetSaturation();
float lightness = color.GetBrightness();
Note that it's not exactly what you've asked for (see differences between HSL and HSV and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably easy to add.
The EasyRGB has many color space conversions. Here is the code for the RGB->HSV conversion.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just calculations.
found via Google
This is the VB.net version which works fine for me ported from the C code in BlaM's post.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.
Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
Dim i As Integer
Dim f, p, q, t As Double
If (s = 0) Then
' achromatic (grey)
r = v
g = v
b = v
Exit Sub
End If
h /= 60 'sector 0 to 5
i = Math.Floor(h)
f = h - i 'factorial part of h
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
Select Case (i)
Case 0
r = v
g = t
b = p
Exit Select
Case 1
r = q
g = v
b = p
Exit Select
Case 2
r = p
g = v
b = t
Exit Select
Case 3
r = p
g = q
b = v
Exit Select
Case 4
r = t
g = p
b = v
Exit Select
Case Else 'case 5:
r = v
g = p
b = q
Exit Select
End Select
End Sub
I've ended up here by having the same need.
Bellow I'm sharing the best and simpler solution I could find so far.
This is a modified answer from Greg's (found here); but with a humbler and understandable code.
For those who are learning I've added a few references that are worth checking for the sake of understanding.
References
"Lukas Stratmann" HSV Model Tool (Incl. Other Model Systems: CMY / CMYK / HSL)
"The HSV Color Model in Graphic Design"
"Formula to Determine Perceived Brightness of RGB Color"
Fastest Formula to Get Hue from RGB
"Color Conversion Algorithms"
"Program to Change RGB color model to HSV color model"
"RGB to HSV Color Conversion Algorithm"
"RGB to HSV Color Space Conversion (C)"
"How to Convert RGB Color to HSV"
Code
/// <summary> Convert RGB Color to HSV. </summary>
/// <param name="color"></param>
/// <returns> A double[] Containing HSV Color Values. </returns>
public double[] rgbToHSV(Color color)
{
double[] output = new double[3];
double hue, saturation, value;
int max = Math.Max(color.R, Math.Max(color.G, color.B));
int min = Math.Min(color.R, Math.Min(color.G, color.B));
hue = color.GetHue();
saturation = (max == 0) ? 0 : 1d - (1d * min / max);
value = max / 255d;
output[0] = hue;
output[1] = saturation;
output[2] = value;
return output;
}
FIRST: make sure you have a color as a bitmap, like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
(e is from the event handler wich picked my color!)
What I did when I had this problem a whilke ago, I first got the rgba (red, green, blue and alpha) values.
Next I created 3 floats: float hue, float saturation, float brightness. Then you simply do:
hue = yourcolor.Gethue;
saturation = yourcolor.GetSaturation;
brightness = yourcolor.GetBrightness;
The whole lot looks like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
float hue;
float saturation;
float brightness;
hue = paintcolor.GetHue();
saturation = paintcolor.GetSaturation();
brightness = paintcolor.GetBrightness();
If you now want to display them in a label, just do:
yourlabelname.Text = hue.ToString;
yourlabelname.Text = saturation.ToString;
yourlabelname.Text = brightness.ToString;
Here you go, you now have RGB Values into HSV values :)
Hope this helps

Converting ARBG to RGB with alpha blending

Let's say that we have an ARGB color:
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is Color.FromARGB(255, 162, 133, 255);
The solution should work like this:
Color blend = Color.White;
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255);
What is ToRGB's implementation?
It's called alpha blending.
In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.
alpha=argb.alpha()
r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()
g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()
b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()
note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly
Edited to add:
If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :).
In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).
I know this is an old thread, but I want to add this:
Public Shared Function AlphaBlend(ByVal ForeGround As Color, ByVal BackGround As Color) As Color
If ForeGround.A = 0 Then Return BackGround
If BackGround.A = 0 Then Return ForeGround
If ForeGround.A = 255 Then Return ForeGround
Dim Alpha As Integer = CInt(ForeGround.A) + 1
Dim B As Integer = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B >> 8
Dim G As Integer = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G >> 8
Dim R As Integer = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R >> 8
Dim A As Integer = ForeGround.A
If BackGround.A = 255 Then A = 255
If A > 255 Then A = 255
If R > 255 Then R = 255
If G > 255 Then G = 255
If B > 255 Then B = 255
Return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B))
End Function
public static Color AlphaBlend(Color ForeGround, Color BackGround)
{
if (ForeGround.A == 0)
return BackGround;
if (BackGround.A == 0)
return ForeGround;
if (ForeGround.A == 255)
return ForeGround;
int Alpha = Convert.ToInt32(ForeGround.A) + 1;
int B = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B >> 8;
int G = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G >> 8;
int R = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R >> 8;
int A = ForeGround.A;
if (BackGround.A == 255)
A = 255;
if (A > 255)
A = 255;
if (R > 255)
R = 255;
if (G > 255)
G = 255;
if (B > 255)
B = 255;
return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B));
}
if you don't need to know this pre-render, you could always use the win32 method of getpixel, I believe.
Note: typing on iPhone in the middle of Missouri with no inet access. Will look up real win32 example and see if there is a .net equivalent.
In case anyone cares, and doesn't want to use the (excellent) answer posted above, you can get the color value of a pixel in .Net via this link MSDN example

Categories