简体   繁体   English

如何从字节数组C#创建Managed.Graphics.Direct2D.Bitmap对象

[英]How create Managed.Graphics.Direct2D.Bitmap object from byte array c#

I am traying to make video player. 我正在制作视频播放器。 I want draw images with sharpdx sdk because of cpu isue. 由于cpu isue,我想使用sharpdx sdk绘制图像。 But I have an isue. 但是我有一个问题。 I am getting frames as byte array. 我正在将帧作为字节数组。 Pixel format of images are BGRA32. 图像的像素格式为BGRA32。 I wrote following code to convert it. 我编写了以下代码进行转换。 But it gives to me error "Value does not fall within the expected range". 但这给我带来错误“值不在预期范围内”。

My code is : 我的代码是:

private Bitmap getBitmap(byte[] frame) {
   return RenderTarget.CreateBitmap(new SizeU((uint)img_w, (uint)img_h), frame, 0, new BitmapProperties(new PixelFormat(DxgiFormat.B8G8R8A8_UNORM, AlphaMode.Ignore), 100, 100));
}

Note : img_w = 720, img_h = 576, length of frame array = 720 * 576 * 4 注意:img_w = 720,img_h = 576,帧数组的长度= 720 * 576 * 4

I tried that first of all create image than copy data to image. 我首先尝试创建映像,而不是将数据复制到映像。 But it doesn't work also. 但这也不起作用。 It copies first row to all row. 它将第一行复制到所有行。 在此处输入图片说明

Left image is original image, right is created by copy from byte array . 左图像是原始图像,右图像是通过字节数组复制创建的。 I used following code to create this image. 我使用以下代码创建此图像。

private Bitmap getBitmap(byte[] frame) {
        var bmp = RenderTarget.CreateBitmap(new SizeU((uint)img_w, (uint)img_h), IntPtr.Zero, 0, new BitmapProperties(new PixelFormat(DxgiFormat.B8G8R8A8_UNORM, AlphaMode.Ignore), 100, 100));
        bmp.CopyFromMemory(new RectU(0, 0, (uint)img_w, (uint)img_h), frame, 0);

        return bmp;
    }

The last parameter, where you have "0" needs to be the "pitch" of the source bitmap. 最后一个参数(您具有“ 0”的位置)必须是源位图的“间距”。

From ID2D1Bitmap::CopyFromMemory method : ID2D1Bitmap :: CopyFromMemory方法

The stride, or pitch, of the source bitmap stored in srcData. 存储在srcData中的源位图的步幅或音调。 The stride is the byte count of a scanline (one row of pixels in memory). 跨度是扫描线(内存中的一行像素)的字节数。 The stride can be computed from the following formula: pixel width * bytes per pixel + memory padding. 可通过以下公式计算步幅:像素宽度*每个像素字节+内存填充。

You are using 4 bytes per pixel, and the source rows probably have no padding, so try 4 * img_w : 您正在使用每个像素4个字节,并且源行可能没有填充,因此请尝试4 * img_w

bmp.CopyFromMemory(new RectU(0, 0, (uint)img_w, (uint)img_h), frame, 4 * img_w);

Putting "0" here means "At each row, add 0 to the start address of the previous row, to find the start of the next row." 在此处添加“ 0”的意思是“在每一行中,将0添加到上一行的开始地址,以找到下一行的开始。” This means it keeps taking rows from the same memory address, explaining why you see "first row repeated". 这意味着它将不断从相同的内存地址获取行,从而解释了为什么看到“重复的第一行”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM