如何使用ASP.NET从SQL Server显示图像?

时间:2012-07-01 17:34:30

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

这是我的类(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)

2 个答案:

答案 0 :(得分:5)

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

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

修改

只需使用带有cource tet的img标记到上述aspx网页。例如:

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

答案 1 :(得分:3)

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

阅读本文,一个非常好的例子

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