[英]How can I copy byte[] into byte[,,]?
该问题与以下内容有关: 如何更快地将位图转换为byte [,,]?
我有byte [],它具有:
[r0,g0,b0,r1,g1,b1 ...]
(r0是第零个像素的r值,依此类推)
如何快速将其复制到byte [,,]?
还是我可以从BitmapData
直接获得byte [,,]?
根据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; }
}
}
好的,假设您已经将数据存储在一维字节数组中。 您是否真的需要将其推入三维阵列中? 如果您想要的只是一种访问像素数据的简便方法,为什么不简单地向该数组编写如此简单的接口呢? 遵循以下原则:
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; }
}
}
如何使用类似这样的方式来方便地访问离散字节:
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]; } }
}
您甚至可以简化操作,使用以下方法重载this []:
public Color this[int x, int y]
{ get { return Color.FromArgb(this[x,y,0], this[x,y,1], this[x,y,2]); }
您还可以考虑使用System.Drawing
的内置Bitmap
。 这是一个具有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]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.