Convert byte array to 2D XNA texture

I have a byte array representing an image.

Each byte represents an intensity value (0-255) of either R, G, or B of a specific pixel. So for a 640x480 image the size of the byte array is 640 * 480 * 3 (each pixel has 3 bytes representing it).

The byte is in pixel order. For example:

image[0] = the R value of x=0 y=0 
image[1] = the G value of x=0 y=0
image[2] = the B value of x=0 y=0
image[3] = the R value of x=1 y=0



I am wondering what is the most efficient way to do this for a screen in XNA?

My thoughts are to do the following.

  • Create a new Texture2d object
  • During the draw () method, loop through the byte array and set the values ​​in the Texture2D object
  • Draw this filled object on the screen.

Is this the fastest way to do it? I can also store the byte array in a different order / format if more efficient. Is there a downside to executing the loop during the draw () method? Would it be better to do this during update ()?


I tried using setData () in Texture2D inorder to create a new texture every time the byte array is updated (usually after a frame). Fps is now below 15, while up to 60 seconds. The code looks like this:

    public static Texture2D getImageFrame(GraphicsDevice gd)
        if (cameraTex == null)
            cameraTex = new Texture2D(gd, 640, 480, false, SurfaceFormat.Color);
        return cameraTex;


Which is called a draw () loop.

Should there really be a more efficient way to do this?


source to share

1 answer

Depending on how the byte array is updated (perhaps worth noting), perhaps you can update a smaller segment of the texture using the SetData overloads that use the index and count parameters.

Obviously, you need to add some way of keeping track of which areas of the pixels were last changed for this to work (again depends on the structure of your program). Anyway, I had similar success when you recently painted a blood splatter texture on a different texture, and using this method managed to minimize bumps.

public void SetData (T [] data, int startIndex, int elementCount)

public void SetData (int level, Nullable rect, T [] data, int startIndex, int elementCount)



All Articles