将字节数组转换为double的问题

Eyl*_*yla 0 c# winforms

我有一个问题,使用转换字节数组到双数组BitConverter.ToDouble().

只需我的程序将选择一个图像,然后将图像转换为字节数组.然后它将字节数组转换为双数组.

当我将字节数组转换为double时,我将在循环结束前得到此错误的问题.

(目标数组不够长,无法复制集合中的所有项目.检查数组索引和长度.)

该错误恰好发生在array.Length-7位置,该位置是阵列上最后一个位置之前的第七个位置.

我需要帮助来解决这个问题,这是我的代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

Sap*_*pph 6

BitConverter.ToDouble(byte[], int)
Run Code Online (Sandbox Code Playgroud)

使用8个字节构造一个64位双精度,这解释了你的问题(一旦你到达第7个到最后一个元素,就不再剩下8个字节了).根据你如何设置你的循环,我猜这不是你想要做的.

我想你想要的东西是这样的:

for(int i = 0; i < index; i++)
{
    dImageArray[i] = (double)imageArray[i];
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 或使用LINQ,只是为了好玩:

double[] dImageArray = imageArray.Select(i => (double)i).ToArray();
Run Code Online (Sandbox Code Playgroud)

另一方面...

如果BitConverter 绝对你想要什么,那么你就需要这样的东西:

double[] dImageArray = new double[imageArray.Length / 8];
for (int i = 0; i < dImageArray.Length; i++)
{
    dImageArray[i] = BitConverter.ToDouble(imageArray, i * 8);
}
Run Code Online (Sandbox Code Playgroud)

同样,根据您的代码,我认为第一个解决方案就是您所需要的.