2

I have something like that:

[StructLayout(LayoutKind.Explicit)] public struct PixelColorRGBA { [FieldOffset(0)] public UInt32 ColorBGRA; [FieldOffset(0)] public byte Blue; [FieldOffset(1)] public byte Green; [FieldOffset(2)] public byte Red; [FieldOffset(3)] public byte Alpha; } 

What is the fastest way to copy PixelColorRGBA[w, h] to byte[w * h * 4] and vise versa?

3 Answers 3

1

I end up with the following code:

var source = new PixelColorRGBA[1000, 1000]; var destination = new byte[4000000]; { var start = DateTime.Now; unsafe { for (var q = 0; q < 100; q++) fixed (PixelColorRGBA* tmpSourcePtr = &source[0, 0]) { var sourcePtr = (IntPtr) tmpSourcePtr; Marshal.Copy(sourcePtr, destination, 0, 4000000); } } Console.WriteLine("MS: " + DateTime.Now.Subtract(start).TotalMilliseconds); } 

It takes 62 ms on my computer.

Sign up to request clarification or add additional context in comments.

Comments

1

Try the following

 PixelColorRGBA[,] source = ...; byte[] dest = source .Cast<PixelColorRGBA>() .SelectMany(x => new byte[] { x.Blue, x.Green, x.Red, x.Alpha }) .ToArray(); 

1 Comment

@breethe it's the fastest to type ;)
0

You can use

System.Buffer.BlockCopy(myArray, 0, byteArray, 0, length) 

or

System.Runtime.InteropServices.Marshal.Copy(myArray, 0, destPtr, length); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.