Reputation: 4333
I have code which convert byte array to bitmap.. (In my Project I cannot use MemoryStream or others bitmap converter.)
Here is my code.
public static Bitmap ConvertBitMap(int width, int height, byte[] imageData)
{
var data = new byte[width * height * 4];
int o = 0;
for (var i = 0; i < width * height ; i++)
{
var value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
...
...
..
..
}
When I run application i says "System.IndexOutOfRangeException: Index was outside the bounds of the array."
Here is arrayData information :
data ------> {byte[614400]}
imageData ---> {byte[105212]}
Could you please anyone help me about fixing this issue ? How can i handle this outside bounds problem ?
Upvotes: 2
Views: 638
Reputation: 754725
The problem here is that the length of imageData
is less than height * width
. Hence you eventually get an exception on this line because i
is greater than imageData.Length
var value = imageData[i];
Consider the sizes that you posted in the question
The size of data
was calculated as height * width * 4
hence we can calculate height * width
by dividing by 4
and we end up with height * width == 153600
. This is clearly larger than 105212
and hence you end up accessing outside the bounds of the array
Upvotes: 1
Reputation: 1976
I'm not sure why this is happening, but the issue is that imageData size is not equal to width*height
This code should fix it (though it might not be what you're looking for it to do)
public static Bitmap ConvertBitMap(int width, int height, byte[] imageData)
{
var data = new byte[imageData.Length * 4];
int o = 0;
for (var i = 0; i < imageData.Length ; i++)
{
var value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
...
...
..
..
}
Upvotes: 1