I have a problem to convert an byte array to double array using BitConverter.ToDouble().
Simply my program will select an image then convert the image to byte array.
Then it will convert the byte array to double array.
The problem that when I convert the byte array to the double I will get this error before the loop finish.
(Destination array is not long enough to copy all the items in the collection. Check array index and length.)
The error happen exactly at array.Length-7 position which is last seventh position before the last position on the array.
I need help to solve this problem and here is my code:
private Bitmap loadPic;
byte[] imageArray;
double[] dImageArray;
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(open.FileName);
loadPic = new Bitmap(pictureBox1.Image);
}
}
catch
{
throw new ApplicationException("Failed loading image");
}
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void btnConvert_Click(object sender, EventArgs e)
{
imageArray = imageToByteArray(loadPic);
int index = imageArray.Length;
dImageArray = new double[index];
for (int i = 0; i < index; i++)
{
dImageArray[i] = BitConverter.ToDouble(imageArray,i);
}
}
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, ImageFormat.Gif);
return ms.ToArray();
}
uses eight bytes to construct a 64-bit double, which explains your problem (once you get to the 7th to last element, there are no longer eight bytes left). I’m guessing this is not what you want to do, based on how you set up your loop.
I imagine you want something like:
Edit – or using LINQ, just for fun:
On the other hand…
If
BitConverteris definitely what you want, then you’ll need something like:Again, based on your code, I think the first solution is what you need.