使用Marshal.Copy函数将ushort []数组数据复制到位图C#中

时间:2017-02-01 17:33:41

标签: c# arrays bitmap marshalling

据我所知,Marshal.Copy()函数没有重载将数据从ushort []数组复制到位图中。在不更改ushort []数组的情况下,如何在这种情况下将数据导入位图?

//Converting the short array from DepthFrame into a bitmap object for DepthFrame
public static Bitmap ToBitmap(this ushort[] data, int width, int height, PixelFormat format)
{
    var bitmap = new Bitmap(width,height,format);

    var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0,0,bitmap.Width,bitmap.Height), 
                                    ImageLockMode.WriteOnly, bitmap.PixelFormat);
    //Error - has some invalid arguments (ushort[] data)
    Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);
    bitmap.UnlockBits(bitmapData);

    return bitmap;
}

//Depth image frame to bitmap directly
public static Bitmap ToBitmap(this DepthFrame frame)
{
    if (frame == null || frame.FrameDescription.LengthInPixels == 0)
    {
        return null;
    }

    int width = frame.FrameDescription.Width;
    int height = frame.FrameDescription.Height;
    PixelFormat format = PixelFormat.Format32bppRgb;

    ushort[] pixelData = new ushort[width * height];

    frame.CopyFrameDataToArray(pixelData);

    return pixelData.ToBitmap(width, height, format);
}

0 个答案:

没有答案