C# : Matrice de couleur
La matrice de couleur (ColorMatrix) est une classe du framework .Net permettant d’appliquer à tous les pixels d’une image une transformation dans au sein de leur espace de couleur (RGBAW).
Variation de teinte (rotation matricielle)
Pour faire une variation de la teinte (variation dans l’espace HSL sans toucher à la saturation ni à la luminosité), il faut effectuer une rotation autour de l’axe {{0,0,0},{1,1,1}} dans l’espace RGB. Pour cela :
colormatrix.cs
private void RotateColors(Bitmap image, float degrees)
{
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
double r = degrees * System.Math.PI / 180; // degrees to radians
float cosR = (float)Math.Cos(r);
float sinR = (float)Math.Sin(r);
float a = (1 + 2 * cosR) / 3;
float b = ((1 - cosR) - (float)Math.Sqrt(3) * sinR) / 3;
float c = ((1 - cosR) + (float)Math.Sqrt(3) * sinR) / 3;
float[][] colorMatrixElements = {
new float[] {a, b, c, 0, 0},
new float[] {c, a, b, 0, 0},
new float[] {b, c, a, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
using (Graphics g = Graphics.FromImage(image))
{
g.DrawImage(
image,
new Rectangle(0, 0, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
}
}