2016-04-02 112 views
0

我有一个工作代码,可以访问确定的像素值,如果给定的图像有8,24或32bpp。这里的是代码:如何从1,2,4 bpp图像访问像素?

使用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像素值?

+0

只是抛出一个异常。这些像素格式在20年前已经过时。好消息,调色板是一个主要的皮塔饼。投掷8bpp以及不正确的代码不会造成任何损害。 –

+0

而我仍然有一个4bpp图像,问题不是*我应该如何面对1,2,4和8bpp图像?*,但是**如何继续获取像素并使用该图像执行其他操作?** 。 –

回答

0

在尝试读取像素值之前,我正在将图像转换为其他Format。这解决了我的问题。