简体   繁体   中英

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. But I have an isue. I am getting frames as byte array. Pixel format of images are 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

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.

From ID2D1Bitmap::CopyFromMemory method :

The stride, or pitch, of the source bitmap stored in 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 :

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." This means it keeps taking rows from the same memory address, explaining why you see "first row repeated".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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