【问题标题】:How to show a image in database in the image control of Asp.net?如何在 Asp.net 的图像控件中显示数据库中的图像?
【发布时间】:2011-01-29 17:45:38
【问题描述】:

如何在 Asp.net 的图像控件中显示数据库中的图像?我们必须在 asp.net 页面中显示员工的图像及其详细信息,但问题是如何在 asp.net 图像控件上显示图像,因为图像控件通过属性 ImageUrl 拍照。

请指导....

【问题讨论】:

    标签: c# .net asp.net


    【解决方案1】:

    您可以创建一个 HttpHandler(ashx) 页面,该页面将接受一个查询字符串并将其设置为图像控件的 imageUrl 属性

    <asp:image id="imgEmployee" imageUrl="DisplayImage.ashx?employeeId=<someId>"/>
    

    现在在 DisplayImage.ashx 中,您可以像下面这样覆盖 Processrequest:-

        public void ProcessRequest (HttpContext context) 
        { 
              int employeeId;
              if (context.Request.QueryString["employeeId"] != null)
       employeeId = Convert.ToInt32(context.Request.QueryString["employeeId"]);
              else
                throw new ArgumentException("No parameter specified");
    
            byte[] imageData= ;// get the image data from the database using the employeeId Querystring
            Response.ContentType = "image/jpeg"; // You can retrieve this also from the database
            Response.BinaryWrite(imageData);
    
        } 
    

    Web.config 更改:-

    <httpHandlers>
      <add verb="*" path="img/*" type="DisplayImage"/>
    </httpHandlers>
    

    详细信息herehere

    希望这会有所帮助..

    【讨论】:

    • 我认为你的问题弄错了。我必须在 asp.net 的图像控件中显示图像,而不仅仅是在网页上。
    • @HotTester,上面的代码/概念将在 IMG 控件中显示图像。为了进一步解释,假设您有一个页面 (EmployeeDetails.aspx),其中有图像控件,其 imageUrl 为“DisplayImage.ashx?employeeId=12”。当您请求“EmployeeDetails.aspx”页面并呈现图像控件时,请求将转到 DisplayImage.ashx(一个 HttpHandler),该请求将输出图像的二进制数据,然后显示在 Employee.aspx 的 Image 控件中。如果我仍然误解了您的问题,请告诉我。
    【解决方案2】:

    这也可以在不创建处理程序的情况下完成。

    //get the image from the database as byte array
    byte[] image = (byte[])dr["image"];
    
    //set the ImageUrl of the Image Control as a Base64 string
    Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image)
    

    或者,如果您还想要 with 和 height,请使用 MemoryStream 创建一个 Image 并获取图像属性。

    using (MemoryStream ms = new MemoryStream(image))
    {
        System.Drawing.Image imageFromDB = System.Drawing.Image.FromStream(ms);
    
        Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
        Image1.Width = imageFromDB.Width;
        Image1.Height = imageFromDB.Height;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 2011-12-18
      相关资源
      最近更新 更多