Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.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# 使用Fopen将位图转换为字节[]_C#_Image - Fatal编程技术网

C# 使用Fopen将位图转换为字节[]

C# 使用Fopen将位图转换为字节[],c#,image,C#,Image,我试图写一个代码,提取位图文件中每个像素的像素颜色值。为此,我将bmp作为位图对象导入,并使用了bitmap.GetPixel(x,y)方法,但速度不够快,不适合我的应用程序。我的一位同事给了我一个建议;我想我可以使用fopen打开文件本身,将字节数据解析为数组。你们有谁知道吗?使用fopen方法不是必须的,我可以使用任何东西 提前感谢。您可以使用不安全代码块,也可以使用。我会这样解决: public static byte[] GetBytesWithMarshaling(Bitmap bit

我试图写一个代码,提取位图文件中每个像素的像素颜色值。为此,我将bmp作为位图对象导入,并使用了bitmap.GetPixel(x,y)方法,但速度不够快,不适合我的应用程序。我的一位同事给了我一个建议;我想我可以使用fopen打开文件本身,将字节数据解析为数组。你们有谁知道吗?使用fopen方法不是必须的,我可以使用任何东西


提前感谢。

您可以使用不安全代码块,也可以使用。我会这样解决:

public static byte[] GetBytesWithMarshaling(Bitmap bitmap)
{
    int height = bitmap.Height;
    int width = bitmap.Width;

    //PixelFormat.Format24bppRgb => B|G|R => 3 x 1 byte
    //Lock the image
    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
    // 3 bytes per pixel
    int numberOfBytes = width * height * 3;
    byte[] imageBytes = new byte[numberOfBytes];

    //Get the pointer to the first scan line
    IntPtr sourcePtr = bmpData.Scan0;
    Marshal.Copy(sourcePtr, imageBytes, 0, numberOfBytes);

    //Unlock the image
    bitmap.UnlockBits(bmpData);

    return imageBytes;
}

没那么容易。您需要将不同的格式从原始数据转换为目标格式,这不是一件容易的工作。至少我知道这么多。您可以使用
byte[]data=System.IO.File.ReadAllBytes('File.bmp')
来获取数据,但我已经谈到了格式设置。fopen()函数与FileStream或File.ReadAllBytes()或Image.FromFile()没有任何更快或不同。关注使用不安全的指针,这是GetPixel()的替代方法。使用Bitmap.LockBits(),有大量的谷歌点击。这是第一个答案,它工作得非常好。非常感谢。但我无法理解封送处理类是关于什么的,以及lockbits方法是做什么的,请您简要解释一下它们好吗?1,lockbits=>在对象的生命周期中,它们在内存中的位置可能会发生变化,例如在垃圾收集之后。为了防止这种行为,位图在内存中被锁定/固定。我认为它的工作原理与固定语句类似。Marshall是一个静态类,它包含一系列方法,用于在托管代码和非托管代码之间进行互操作、分配非托管内存等。