【问题标题】:Image retrieve gives error Index was outside the bounds of the array图像检索给出错误索引超出了数组的范围
【发布时间】:2014-04-24 09:10:38
【问题描述】:

我试图在页面加载时将图像从数据库获取到 img 控件,但我收到此错误。 “指数数组的边界之外。”在“long retrievedBytes = 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();
}

【问题讨论】:

  • 如果这是ASP.Net,你为什么使用&lt;img /&gt;标签而不是&lt;asp:Image /&gt;标签?您的代码甚至看起来都不会编译,while 循环中的随机 &lt;strong&gt; 标记是什么?请提供一个简短的完整示例,说明如何重现您的问题。

标签: c# asp.net


【解决方案1】:

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

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

using (var ms = new MemoryStream())
{
  // Work as usual
}

// Dispose is called automatically, even if there's an unhandled exception

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多