此问题与以下内容有关:How to convert Bitmap to byte[,,] faster?
我有byte [],它有:
[r0,g0,b0,r1,g1,b1 ......]
(r0是第0个像素的r值,依此类推)
如何快速将其复制到byte [,,]?
或者也许我可以从BitmapData
?
答案 0 :(得分:2)
根据Martinho的回答,但也许更快一些(现在没有时间进行基准测试):
struct BitmapDataAccessor
{
private readonly byte[] data;
private readonly int[] rowStarts;
public readonly int Height;
public readonly int Width;
public BitmapDataAccessor(byte[] data, int width, int height)
{
this.data = data;
this.Height = height;
this.Width = width;
rowStarts = new int[height];
for(int y=0;y<height;y++)
rowStarts[y]=y*width;
}
public byte this[int x, int y, int color] // Maybe use an enum with Red = 0, Green = 1, and Blue = 2 members?
{
get { return data[(rowStarts[y] + x) *3 + color]; }
set { data[(rowStarts[y] + x) *3 + color] = value; }
}
public byte[] Data
{
get { return data; }
}
}
答案 1 :(得分:1)
好的,假设您已经将数据存储在一维字节数组中。你真的需要把它推到一个三维阵列吗?如果你想要的只是一种访问像素数据的简单方法,为什么不简单地将这样一个简单的接口写入该数组呢?这些方面的东西:
class BitmapDataAccessor
{
private readonly byte[] data;
private readonly int rows;
private readonly int columns;
public BitmapDataAccessor(byte[] data, int rows, int columns)
{
this.data = data;
this.rows = rows;
this.columns = columns;
}
public byte this[int row, int column, int color] // Maybe use an enum with Red = 0, Green = 1, and Blue = 2 members?
{
get { return data[(row * columns + column) * 3 + color]; }
set { data[(row * columns + column) * 3 + color] = value; }
}
public byte[] Data
{
get { return data; }
}
}
答案 2 :(得分:0)
如何使用这样的东西来方便访问离散字节:
class ByteIndexer
{
private readonly byte[] _bits;
private readonly int _width;
public ByteIndexer(byte[] bits, int width)
{
_bits = bits;
_width = width;
}
public byte this[int x, int y, int c]
{ get { return _bits[(((_width * y) + x) * 3) + c]; } }
}
你甚至可以让它更容易,用[:]重载这个[]
public Color this[int x, int y]
{ get { return Color.FromArgb(this[x,y,0], this[x,y,1], this[x,y,2]); }
答案 3 :(得分:0)
您还可以考虑使用Bitmap
中的内置System.Drawing
。这是一个4x3图像的例子。
var image = new byte[] {255,255,255,0,0,0,255,255,255,0,0,0,
255,255,255,0,0,0,255,127,255,0,0,0,
0,0,0,255,255,255,0,0,0,255,255,255};
Bitmap bmp = new Bitmap(4, 3, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
Marshal.Copy(image, 0, bmpData.Scan0, image.Length);
bmp.UnlockBits(bmpData);
var testPixel = bmp.GetPixel(2, 1);
testPixel将System.Drawing.Color
设置为{Color [A=255, R=255, G=127, B=255]}