图像检索提供错误索引超出了数组的范围。
问题描述:
我正在尝试将页面加载中的图像从数据库转换为img控件但我收到此错误。
索引超出了数组的范围。
I am trying to get image at pageload from database to a img control but i receive this error.
"Index was outside the bounds of the array."
<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();
}
答
GetBytes方法中的startIndex参数是指目标数组中的起始索引,而不是源。只需在那里使用0。
The startIndex parameter in the GetBytes method is referring to the starting index in the target array, not the source. Just use 0 there.