Question

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?

Was it helpful?

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

OTHER TIPS

What is the format of the image? How many bytes per pixel?

Per the documentation, you can see this error when the size of the array you are passing to GetData is too small to contain the render target's data. This seems to be the likely culprit here, since you are allocating 1024x1024 bytes. Unless you are using the Alpha8 format, each pixel in the render target is likely going to occupy at least two bytes of space. You need to figure out how many bytes are used per-pixel of your render target (by checking the Format property, for example). Once you know that, multiply your 1024 * 1024 calculation by that value.

For example, allocate an array of size 1024 * 1024 * 3 if you know your render target uses three bytes per pixel, et cetera.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top