如何从1,2,4 bpp图像中访问像素?

时间:2016-04-02 02:24:04

标签: c# image pixel bitmapsource

如果给定的图像有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像素值?

1 个答案:

答案 0 :(得分:0)

我正在尝试读取像素值之前将图像转换为其他class RenderView:UIView { var pointsToDraw:[Int] = [] { didSet { self.setNeedsDisplay() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.backgroundColor = UIColor.whiteColor() } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext(); CGContextClearRect(context, self.bounds); CGContextSetLineWidth(context, 3); UIColor.yellowColor().set() if pointsToDraw.count > 4 { CGContextMoveToPoint(context, CGFloat(pointsToDraw[0]), CGFloat(pointsToDraw[1])) for i in 2..<pointsToDraw.count { if i % 2 == 0 { CGContextAddLineToPoint(context, CGFloat(pointsToDraw[i]), CGFloat(pointsToDraw[i + 1])) } } } // Draw CGContextStrokePath(context); } } 。这解决了我的问题。