【问题标题】:Serving an Image stored in a database on an aspx page在 aspx 页面上提供存储在数据库中的图像
【发布时间】:2011-04-02 14:22:54
【问题描述】:

我正在拉回存储在 SQL Server 数据库的列中的图像。

我需要在一个 aspx 页面上提供这个。

我该怎么做?

【问题讨论】:

标签: .net asp.net sql-server


【解决方案1】:

您首先获取Page.Response,然后调用BinaryWrite 或使用Stream directly

另外,我建议将图像存储在文件系统上,而不是数据库上。

【讨论】:

    【解决方案2】:

    在html页面中,你需要渲染一个<img>标签,其中src属性指向另一个页面(或ashx处理程序)。在其他页面/处理程序中,您生成的 only 输出是图像的二进制数据(可能还有一些 http 标头)。
    使用参数指定图片。

    【讨论】:

      【解决方案3】:

      我将创建一个图像元素,其中 src 属性指向一个带有查询字符串中图像 ID 的 ashx 处理程序。在这个处理程序中,您可以有以下代码:

              string ImageId = Request.QueryString["img"];
              string sqlText = "SELECT img_data, img_contenttype FROM Images WHERE img_pk = " + ImageId;
      
              using (var connection = new SqlConnection("your connection string"))
              {
                  using (var command = new SqlCommand(sqlText, connection))
                  {
                      connection.Open();
                      using (SqlDataReader dr = command.ExecuteReader())
                      {
                          if (dr.Read())
                          {
                              Response.Clear();
                              Response.ContentType = dr["img_contenttype"].ToString();
                              Response.BinaryWrite((byte[]) dr["img_data"]);
                              Response.End();
                          }
                      }
                  }
              }
      

      【讨论】:

        【解决方案4】:

        从数据库中检索它,使用 System.Drawing.Image 类从二进制转换为图像,然后将图像保存在临时文件夹中。在html/ascx/aspx等中的<img>标签中给出temp文件夹的路径

        C#:

         MemoryStream ms = new MemoryStream(binaryImage);
         Bitmap BMP = new Bitmap(ms);
         String path = Server.MapPath("..\\Temp");
        
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
         }
        
         FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, path);
        
         if (SecurityManager.IsGranted(writePermission))
         {
             System.Drawing.Image img = new System.Drawing.Bitmap(ms);
             img.Save(path + "\\xyz.jpg", ImageFormat.Jpeg);
         }
        

        HTML/ASPX:

        <img src="Temp/xyz.jpg">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-20
          相关资源
          最近更新 更多