我正在用C#制作图像编辑程序,我想要的功能之一是反转颜色。
截至目前,我有以下代码只加载图像并将颜色放入二维数组中:
if (fd.ShowDialog() == DialogResult.OK)
{
//store the selected file into a bitmap
bmp = new Bitmap(fd.FileName);
//create the arrays that store the colours for the image
//the size of the arrays is based on the height and width of the bitmap
//initially both the original and transformedPic arrays will be identical
original = new Color[bmp.Height, bmp.Width];
transformedPic = new Color[bmp.Height, bmp.Width];
//load each color into a color array
for (int i = 0; i < bmp.Height; i++)//each row
{
for (int j = 0; j < bmp.Width; j++)//each column
{
//assign the colour in the bitmap to the array
original[i, j] = bmp.GetPixel(j, i);
transformedPic[i, j] = original[i, j];
}
}
this.Refresh();
}
}
我对于反转颜色的概念以及如何操纵二维数组中的值以反映像素的反转颜色完全难以理解。我对编程非常陌生,所以非常感谢任何帮助。
编辑:(不工作)
//code to invert
byte A, R, G, B;
Color pixelColor;
for (int i = 0; i < bmp.Height; i++)
{
for (int j = 0; j < bmp.Width; j++)
{
pixelColor = original[i, j];
A = (byte)Math.Abs(255 - pixelColor.A);
R = (byte)Math.Abs(255 - pixelColor.R);
G = (byte)Math.Abs(255 - pixelColor.G);
B = (byte)Math.Abs(255 - pixelColor.B);
bmp.SetPixel(i, j, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
transformedPic[i, j] = bmp.GetPixel(i, j);
}
}
答案 0 :(得分:0)
要反转整个图像,请尝试以下操作:
var original = (BitmapSource)image;
var bmp = new WritableBitmap( original );
bmp.Lock();
var bgra = new byte[bmp.PixelHeight * bmp.PixelWidth * 4];
bitmap.CopyPixels( bgra, bmp.PixelWidth * 4, 0 );
for( var y = 0; y < bmp.PixelHeight; y++ )
for( var x = 0; x < bmp.PixelWidth; x++ )
{
var offset = y * bmp.PixelWidth * 4 + x * 4;
bgra[offset + 0] = (byte)(255 - bgra[offset + 0] );
bgra[offset + 1] = (byte)(255 - bgra[offset + 1] );
bgra[offset + 2] = (byte)(255 - bgra[offset + 2] );
}
bmp.WritePixels( new Int32Rect( 0, 0, width, height ), bgra, bmp.PixelWidth * 4, 0 );
bmp.Unlock();
bmp.Freeze();