BLOG.CSHARPHELPER.COM: Manipulate image pixels using a class with simple pixel get and set methods in C#
Manipulate image pixels using a class with simple pixel get and set methods in C#
The example Manipulate image pixels very quickly using LockBits wrapped in a class in C# shows how to build a class that lets you access an image's pixels very quickly but to do so you need to manipulate the pixels' red, green, and blue components in a large byte array. That means you need to calculate offsets into that array, which can be confusing.
The version of the Bitmap24 class provided by this example provides GetPixel, SetPixel, GetRed, SetRed, GetGreen, SetGreen, GetBlue, and SetBlue methods to make working with pixels easier.
// Provide easy access to the color values. public void GetPixel(int x, int y, out byte red, out byte green, out byte blue) { int i = y * m_BitmapData.Stride + x * 3; blue = ImageBytes[i++]; green = ImageBytes[i++]; red = ImageBytes[i]; } public void SetPixel(int x, int y, byte red, byte green, byte blue) { int i = y * m_BitmapData.Stride + x * 3; ImageBytes[i++] = blue; ImageBytes[i++] = green; ImageBytes[i] = red; } public byte GetRed(int x, int y) { int i = y * m_BitmapData.Stride + x * 3; return ImageBytes[i + 2]; } public void SetRed(int x, int y, byte red) { int i = y * m_BitmapData.Stride + x * 3; ImageBytes[i + 2] = red; } public byte GetGreen(int x, int y) { int i = y * m_BitmapData.Stride + x * 3; return ImageBytes[i + 1]; } public void SetGreen(int x, int y, byte green) { int i = y * m_BitmapData.Stride + x * 3; ImageBytes[i + 1] = green; } public byte GetBlue(int x, int y) { int i = y * m_BitmapData.Stride + x * 3; return ImageBytes[i]; } public void SetBlue(int x, int y, byte blue) { int i = y * m_BitmapData.Stride + x * 3; ImageBytes[i] = blue; }
Comments