在ASP.NET C#中将字节流式传输到图像
我有一个存储在我的SQL Server数据库中的图像与我的用户数据一起存储,我一次检索所有这些数据。
现在我在我想要显示的页面上直接使用byte []。 我如何将它放在我的WebControls.Image中? 我不想调用HttpHandler并再次调用数据库。
这显然只是将它输出到整个页面。
Context.Response.BinaryWrite(user.Picture.ToArray());
如果是小图像,则将其作为base64编码数据输出到图像标记中。 请参阅此处了解类似情况 。
但是在99.9%的情况下,你会创建一个返回图像的HttpHandler。 我认为这是最简单,最快捷的方式。
将字节数组包装在MemoryStream对象中并将其放在ASP.NETs Cache中。
MemoryStream ms = new MemoryStream(user.Picture.ToArray()); Guid imageGuid = new Guid(); HttpRuntime.Cache.Add(imageGuid.ToString(), ms, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
然后使用处理程序(.ashx)将其从缓存中取出并将其发送到客户端。
string imageGuid = context.Request.QueryString[image]; MemoryStream ms = (MemoryStream)HttpRuntime.Cache[imageGuid]; // configure context.Response with appropriate content type and cache settings // ** Edit ** // It seems I need to be more explicit with regard to the above comment:- context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetLastModified(DateTime.UtcNow); context.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(2); context.Response.Cache.SetMaxAge(TimeSpan.FromHours(2)); context.Response.Cache.SetValidUntilExpires(true); ms.WriteTo(context.Response.OutputStream);
现在您可以从Cache中删除MemoryStream。
HttpRuntime.Cache.Remove(imageGuid);
创建单独的页面,您将在其中创建图像,例如:image.aspx并在其他页面上使用它
number是数据库中图像的id
您需要一个IHttpHander
,它会将图像字节和正确的Content-Type
写入响应流。 看到这个 , 这个和这个 。
我很确定你不能在页面本身做到这一点。
如果您不想创建HTTP处理程序来输出图像,那么您可以选择创建一个单独的aspx
页面。 将img
标记的src
设置为指向该页面,在查询字符串中传递某种ID,以便可以从数据库中提取图像数据。
话虽如此,设置一个aspx
页面来做这件事并不比设置一个ashx
更快或更容易。 我建议以正确的方式执行此操作并创建HTTP处理程序。