Here is my class (product.cs) where is the method to insert the 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 of 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’d like to know how can I display this image?
Would I have to read the byte[] from sql (SELECT), convert to string and so convert to byte[]? And after do that convert to bitmap (System.Drawing). But how I show this bitmap in a aspx page?
I’ve no idea how to do it. Please help!! :]
Thanks
Obs.: In SQL Server, the column image is of type varbinary(MAX).
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Create a web page that returns the image. You would select the bytes from the database (as you have already code written to insert, I think you know how to select). Once you have the 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 a img tag with the cource tet to the aforementioned aspx web page. Eg:
<img src="https://www.example.com/image.aspx?id=1" alt="image" />
Method 2
You need to use a handler to do this
Read this, a very nice example
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0