none
How can I display an image from Sql Server database using asp.net c# RRS feed

  • Pergunta

  • Here is my class (product.cs) where is the method to insert the image:

    public static void InsertProductIMG(byte[] image, string contentType) //Insere Produto.
            {
                string cs = "Data Source=(local);Initial Catalog=SiteTD;Integrated Security=True";
                string comandoSql = "INSERT INTO [SiteTD].[dbo].[produto] (image, ContentType) VALUES (@image, @contentType)";
    
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    conn.Open();
                    using (SqlTransaction trans = conn.BeginTransaction())
                    {
                        try
                        {
                            SqlCommand cmd = new SqlCommand(comandoSql, conn, trans);
                            SqlParameter[] parms = new SqlParameter[2];
                            parms[0] = new SqlParameter("@imagem", imagem);
                            parms[1] = new SqlParameter("@contentType", contentType);
    
                            foreach (SqlParameter p in parms)
                            {
    
                                cmd.Parameters.Add(p);
                            }
    
                            cmd.ExecuteNonQuery();
                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                            throw (ex);
                        }
                    }
                }
            }

    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, the column image is a varbinary(MAX). I don't know VB, only C# :[

    sexta-feira, 29 de junho de 2012 18:24

Todas as Respostas