Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将位图转换为颜色[]_C#_Arrays_Bitmap - Fatal编程技术网

C# 将位图转换为颜色[]

C# 将位图转换为颜色[],c#,arrays,bitmap,C#,Arrays,Bitmap,我有一个位图,我想转换成一个颜色数组,比使用GetPixel函数更快 到目前为止,我看到人们先将位图转换为字节数组,然后再转换为颜色数组: Bitmap bmBit = (Bitmap)bit; var bitmapData = bmBit.LockBits(new Rectangle(0, 0, bmBit.Width, bmBit.Height), ImageLockMode.ReadWrite, bmBit.PixelFormat); var length = bitma

我有一个位图,我想转换成一个颜色数组,比使用GetPixel函数更快

到目前为止,我看到人们先将位图转换为字节数组,然后再转换为颜色数组:

Bitmap bmBit = (Bitmap)bit;

var bitmapData = bmBit.LockBits(new Rectangle(0, 0, bmBit.Width, bmBit.Height),
        ImageLockMode.ReadWrite, bmBit.PixelFormat);
var length = bitmapData.Stride * bitmapData.Height;
byte[] bytes = new byte[length];
Marshal.Copy(bitmapData.Scan0, bytes, 0, length);
bmBit.UnlockBits(bitmapData);
但这会返回一个带有错误数字的bmBit。
我做错了什么?有没有更好的方法不用先转换为字节数组就可以做到这一点?

位图中像素的存储方式有很多种(16色、256色、每像素24位等),行被填充为4字节的倍数

for (int i = 0; i < bitmapData.Height; i++)
{
    //the row starts at (i * bitmapData.Stride).
    //we must do this because bitmapData.Stride includes the pad bytes.
    int rowStart = i * bitmapData.Stride;        

    //you need to use bitmapData.Width and bitmapData.PixelFormat
    //  to determine how to parse a row. 

    //assuming 24 bit. (bitmapData.PixelFormat == Format24bppRgb)
    if (bitmapData.PixelFormat == PixelFormat.Format24bppRgb)
    {
        for (int j = 0; j < bitmapData.Width; j++)
        {
            //the pixel is contained in:
            //    bytes[pixelStart] .. bytes[pixelStart + 2];
            int pixelStart = rowStart + j * 3;
        }
    }
}
for(int i=0;i
您是否考虑到
Stride
属性包含填充字节?什么是“不正确的数字”?它返回的数字在整个数组中的位置不正确。这些零是填充零吗?在每个
跨步的末尾
字节的长度?它似乎是以一种模式出现的,所以也许我可以删除这些零。我有一个3x3位图,每9个字节有3组零,总共有3组3。