动态渲染asp:ASP.NET中BLOB条目的图像

我想要实现的是这个。我想让用户能够上传图像文件,将图像存储在SQL Server中的BLOB中,然后将此图像用作网站其他页面中的徽标。


我这样做是通过使用


   Response.Clear();

   Response.ContentType = "image/pjpeg";

   Response.BinaryWrite(imageConents);

   Response.End();

但要做到这一点,我在我想要显示图像的地方使用用户控件。我想尽可能使用asp:Image控件,甚至是纯旧的html图像控件。这可能吗?


翻阅古今
浏览 485回答 3
3回答

杨__羊羊

在Web项目中添加“Generic Handler”,将其命名为Image.ashx。像这样实现它:public class ImageHandler : IHttpHandler{&nbsp; &nbsp; public void ProcessRequest(HttpContext context)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; using(Image image = GetImage(context.Request.QueryString["ID"]))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.Response.ContentType = "image/jpeg";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; image.Save(context.Response.OutputStream, ImageFormat.Jpeg);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public bool IsReusable&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}现在只需实现GetImage方法来加载具有给定ID的图像,您就可以使用了<asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" />&nbsp;显示它。您可能还想考虑在处理程序中实现某种形式的缓存。请记住,如果要将图像格式更改为PNG,则需要使用中间MemoryStream(因为PNG需要保存可搜索流)。
打开App,查看更多内容
随时随地看视频慕课网APP