【发布时间】:2016-04-02 02:24:03
【问题描述】:
如果给定图像具有 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 像素值?
【问题讨论】:
-
只要抛出一个异常。这些像素格式在 20 年前就已经过时了。很好摆脱,调色板是一个主要的皮塔饼。也抛出 8bpp,这样您的错误代码就不会造成任何损害。
-
我仍然得到一个 4bpp 图像,问题不是 我应该如何面对 1、2、4 和 8bpp 图像?,而是 我该如何继续获取像素并对该图像执行其他操作?.
标签: c# image pixel bitmapsource