【问题标题】:How can I display an image from SQL Server using ASP.NET?如何使用 ASP.NET 从 SQL Server 显示图像?
【发布时间】:2012-07-02 07:25:15
【问题描述】:

这是我的课(product.cs),插入图片的方法在哪里:

public static void InsertProductIMG(byte[] image, string contentType) 
{
   string cs = "Data Source=(local);Initial Catalog=myApp;Integrated Security=True";
   string comandoSql = "INSERT INTO [myApp].[dbo].[product] (image, ContentType) VALUES (@image, @contentType)";

   using (SqlConnection conn = new SqlConnection(cs))
   {
       conn.Open();

       using (SqlTransaction trans = conn.BeginTransaction())
       {
           SqlCommand cmd = new SqlCommand(comandoSql, conn, trans);
           SqlParameter[] parms = new SqlParameter[2];
           parms[0] = new SqlParameter("@image", image);
           parms[1] = new SqlParameter("@contentType", contentType);
           foreach (SqlParameter p in parms)
           {
              cmd.Parameters.Add(p);
           }

           cmd.ExecuteNonQuery();
           trans.Commit();
       }
    }
}

这是我调用上述方法的apsx页面背后的代码:

byte[] imageBytes = new byte[fupld.PostedFile.InputStream.Length];
product.InsertProductIMG(imageBytes, "image/jpeg");//product is the class where the method is

现在我想知道如何显示这张图片?

我是否必须从 sql (SELECT) 中读取 byte[],转换为字符串,然后再转换为 byte[]?然后将其转换为位图(System.Drawing)。但是我如何在 aspx 页面中显示这个位图呢?

我不知道该怎么做。请帮忙!! :]

谢谢

Obs.:在 SQL Server 中,列 image 的类型为 varbinary(MAX)

【问题讨论】:

  • 我很好奇你为什么扔(前)?而不是仅仅抛出;..你为什么要尝试/捕捉呢?如果你不提交 tran 将自动回滚,未处理的异常会冒泡

标签: c# asp.net sql-server image


【解决方案1】:

创建一个返回图像的网页。您将从数据库中选择字节(因为您已经编写了要插入的代码,我想您知道如何选择)。获得字节后,您需要设置 mime 类型并将字节写入响应流。

var bytesFromDatabase = getImageFromDatabase();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(bytesFromDatabase);

编辑:

只需在前面提到的 aspx 网页上使用带有源代码的 img 标签。例如:

<img src="http://www.example.com/image.aspx?id=1" alt="image" />

【讨论】:

  • 但我需要在特定的地方展示。这样我可以放任何我想放的地方吗?
【解决方案2】:

您需要使用处理程序来执行此操作

阅读这篇文章,一个很好的例子

http://www.dotnetcurry.com/ShowArticle.aspx?ID=129

【讨论】:

  • 7 年了...这仍然非常有用...谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 2010-10-26
  • 2013-08-02
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
相关资源
最近更新 更多