我正在尝试将页面加载中的图像从数据库转换为img控件但我收到此错误。 “指数数组的边界之外。”在行“long retrieveBytes = 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();
}
答案 0 :(得分:1)
startIndex
方法中的GetBytes
参数是指目标数组中的起始索引,而不是源。只需在那里使用0
。
哦,并使用using
而不是手动调用Dispose
:
using (var ms = new MemoryStream())
{
// Work as usual
}
// Dispose is called automatically, even if there's an unhandled exception