如果给定图像具有 8、24 或 32bpp,我有一个工作代码可以访问确定的像素值。这是代码:
使用BitmapSource
:
// Get width and height of bitmap
Width = _source.PixelWidth;
Height = _source.PixelHeight;
// Get total locked pixels count
int pixelCount = Width * Height;
// Get source bitmap pixel format size
Depth = _source.Format.BitsPerPixel;
// Create byte array to copy pixel values
int step = Depth / 8;
Pixels = new byte[pixelCount * step];
_iptr = _data.BackBuffer;
// Copy data from pointer to array
Marshal.Copy(_iptr, Pixels, 0, Pixels.Length);
int count = Depth / 8;
if (count == 0)
count = 1;
//Get start index of the specified pixel
int i = ((y * Width) + x) * count;
if (i > Pixels.Length - count)
throw new IndexOutOfRangeException();
if (Depth == 32) //For 32 bpp get Red, Green, Blue and Alpha
{
byte b = Pixels[i];
byte g = Pixels[i + 1];
byte r = Pixels[i + 2];
byte a = Pixels[i + 3]; // a
clr = Color.FromArgb(a, r, g, b);
}
else if (Depth == 24) //For 24 bpp get Red, Green and Blue
{
byte b = Pixels[i];
byte g = Pixels[i + 1];
byte r = Pixels[i + 2];
clr = Color.FromRgb(r, g, b);
}
else if (Depth == 8) //For 8 bpp get color value (Red, Green and Blue values are the same)
{
byte c = Pixels[i];
clr = Color.FromRgb(c, c, c);
}
并设置像素值:
if (Depth == 32) //For 32 bpp set Red, Green, Blue and Alpha
{
Pixels[i] = color.B;
Pixels[i + 1] = color.G;
Pixels[i + 2] = color.R;
Pixels[i + 3] = color.A;
}
else if (Depth == 24) //For 24 bpp set Red, Green and Blue
{
Pixels[i] = color.B;
Pixels[i + 1] = color.G;
Pixels[i + 2] = color.R;
}
else if (Depth == 8) //For 8 bpp set color value (Red, Green and Blue values are the same)
{
Pixels[i] = color.B;
}
那么,如何访问(获取、设置)1,2 或 4bpp 像素值?