Search code examples
c#xnatexture2drendertarget

Why do I get a "Too Large or Too Small" error when calling Texture2D.GetData?


I need to quickly save an image, and I am using Texture2D.GetData and SetData because simply saving and loading the image is way too slow. The image is 1024x1024.

RenderTarget2D Image = ChunkContainer.GetImg(x, y);
byte[] imageBuffer = new byte[1024 * 1024];
Image.GetData<byte>(imageBuffer);
b.Write(imageBuffer);

I get an ArgumentException error:

"The size of the data passed in is too large or too small for this resource."

So I can't save a 1024x1024 image? Is there a better way of doing this? Why isn't this working?


Solution

  • You are forgetting to add the Bit Depth, which is typically 4 bytes per pixel (1 byte for each: red, green, blue, alpha). Your array should be: 1024 x 1024 x BitDepth