图像检索给出错误Index超出了数组的界限

本文关键字:数组 界限 出错 错误 Index 图像检索 | 更新日期: 2023-09-27 17:59:54

我试图在页面加载时将图像从数据库获取到img控件,但我收到了这个错误。"索引超出了数组的界限。"在第"行"longretrievedBytes=reader.GetBytes(1,startIndex,buffer,0,ChunkSize);"

<img runat="server" id="image" alt="" height="100" width="100"/>
protected void LoadImages()
{
    SqlCommand cmd = new SqlCommand("sps_getimage", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@ad_id", 10010);
    con.Open();
    SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
    if (reader.HasRows)
    {
        reader.Read();
        MemoryStream memory = new MemoryStream();
        long startIndex = 0;
        const int ChunkSize = 256;
        while (true)
        {
            byte[] buffer = new byte[ChunkSize];
            long retrievedBytes = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize);
            memory.Write(buffer, 0, (int)retrievedBytes);
            startIndex += retrievedBytes;
            if (retrievedBytes != ChunkSize)
                break;
        }
        byte[] data = memory.ToArray();
        memory.Dispose();
        image.Src = "data:image/png;base64," + Convert.ToBase64String(data);
    }
    con.Close();
}

图像检索给出错误Index超出了数组的界限

GetBytes方法中的startIndex参数指的是目标数组中的起始索引,而不是源。只需在那里使用0

哦,使用using而不是手动调用Dispose:

using (var ms = new MemoryStream())
{
  // Work as usual
}
// Dispose is called automatically, even if there's an unhandled exception