How can I display an image from SQL Server using ASP.NET?

Here is my class (product.cs) where there is a way to insert an image:

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(); } } } 

Here is the code behind the apsx page where I call the method above:

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

Now I would like to know how I can display this image?

Should I read byte [] from sql (SELECT), convert to string, and therefore convert to byte []? And then convert to a bitmap (System.Drawing). But how do I display this bitmap on an aspx page?

I do not know how to do that. Please help !!:]

thanks

Note. In SQL Server, the image column is of type varbinary(MAX) .

+4
source share
2 answers

Create a web page that returns an image. You would select bytes from the database (since you have already written the code to insert, I think you know how to choose). When you have bytes, you need to set the mime type and write the bytes to the response stream.

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

Edit:

Just use the img tag with the cource theme on the above aspx webpage. For instance:

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

For this you need to use a handler

Read this, a very good example.

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

+3
source

All Articles