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

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

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

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

编辑:

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

 image 

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

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

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