How do I insert image data directly from an asp:Image control, not through file upload control?

Donald Symmons 3,066 Reputation points
2022-12-26T12:23:01.097+00:00

I have a code that inserts image into database table, the image file comes from a file upload control, with a file name. But I want to insert an image that comes directly inside asp:Image control. How do I do this please?

I can't get this part right

 byte[] image;  
            Stream s = FileUpload1.PostedFile.InputStream;  
            BinaryReader br = new BinaryReader(s);  
            image = br.ReadBytes((Int32)s.Length);  

Here is my code that inserts

  protected void Button1_Click(object sender, EventArgs e)  
        {  
            SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security = True");  
            try  
            {  
                byte[] image;  
                Stream s = FileUpload1.PostedFile.InputStream;  
                BinaryReader br = new BinaryReader(s);  
                image = br.ReadBytes((Int32)s.Length);  
      
                string sqlStatement = "INSERT INTO MyTable (email,CreatedBy,Role,fname,faddress,fmail,fphone,CreatedDate,logo) VALUES (@email,@CreatedBy,@Role,@fname,@faddress,@fmail,@fphone,@CreatedDate,@logo)";  
                con.Open();  
                SqlCommand cmd = new SqlCommand(sqlStatement, con);  
                cmd.Parameters.AddWithValue("@email", user.Text.ToString());  
                cmd.Parameters.AddWithValue("@CreatedBy", createby.Text.ToString());  
                cmd.Parameters.AddWithValue("@Role", role.Text.ToString());  
                cmd.Parameters.AddWithValue("@fname", ftxtname.Text.ToString());  
                cmd.Parameters.AddWithValue("@faddress", ftxtaddress.Text.ToString());  
                cmd.Parameters.AddWithValue("@fmail", ftxtmail.Text.ToString());  
                cmd.Parameters.AddWithValue("@fphone", ftxtphone.Text.ToString());  
                cmd.Parameters.AddWithValue("@CreatedDate", DateTime.UtcNow);  
                cmd.Parameters.AddWithValue("@logo", image);  
                cmd.CommandType = CommandType.Text;  
                cmd.ExecuteNonQuery();  
            }  
            catch (SqlException ex)  
            {  
                string msg = "Insert Error:";  
                msg += ex.Message;  
                throw new Exception(msg);  
            }  
            finally  
            {  
                con.Close();  
            }  
        }  
  
Developer technologies ASP.NET Other
Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-12-26T13:48:45.94+00:00

    If I understand, you are asking how to render an image stored in a database table. The standard approach is taking advantage of the ASP.NET Generic handler (ashx). Add -> New Item -> Generic Handler. The generic handler is the URL you'll use in the Image control.

    Write a query to return the file contents in the ashx.

    public class GetFileById : IHttpHandler  
        {  
      
            public void ProcessRequest(HttpContext context)  
            {  
                //Assumes the file path is passed in the query string  
                int Id = 0;  
      
                if (int.TryParse(context.Request.QueryString["id"], out Id))  
                {  
                    string ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;  
                    SqlConnection con = new SqlConnection(ConnectionString);  
      
                    string sqlStatement = @"SELECT [FileContents]  
                                              ,[FileName]  
                                              ,[ContentType]  
                                          FROM [dbo].[Images]  
                                          WHERE ImageId = @ImageId ";  
      
      
                    con.Open();  
                    SqlCommand cmd = new SqlCommand(sqlStatement, con);  
                    cmd.Parameters.AddWithValue("@ImageId", Id);  
                    cmd.CommandType = CommandType.Text;  
      
                    byte[] fileContents = null;  
                    string fileName = string.Empty;  
                    string contentType = string.Empty;  
                     
                    using (SqlDataReader reader = cmd.ExecuteReader())  
                    {  
                        while (reader.Read())  
                        {  
                            fileContents = (byte[])reader[0];  
                            fileName = (string)reader[1];  
                            contentType = (string)reader[2];  
                        }  
                    }  
      
                    HttpResponse response = context.Response;  
                    response.ContentType = "contentType";  
                    response.AppendHeader("Content-Disposition", "filename=" + fileName);  
      
                    response.OutputStream.Write(fileContents, 0, fileContents.Length);    
                    response.End();  
                }  
      
            }  
      
            public bool IsReusable  
            {  
                get  
                {  
                    return false;  
                }  
            }  
        }  
    

    The handler fetches the file contents by the primary key. Use whatever filter makes sense for your application. Also, the table holds content-type which is go to have so you know what file type the user uploaded.

    Finally, just use the ashx file to render the image. I place the ashx file in a FileHandler folder.

    <asp:Image ID="Image1" runat="server" ImageUrl="/FileHandler/GetFileById.ashx?id=1" />  
    

  2. Albert Kallal 5,586 Reputation points
    2022-12-27T05:00:18.563+00:00

    You can do it like this:

    Say this markup (button + image)

            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Show Image" Width="127px" />  
            <br />  
            <br />  
            <asp:Image ID="Image1" runat="server" Height="401px" Width="455px" />  
    

    And code for the button is this:

        protected void Button1_Click(object sender, EventArgs e)  
        {  
            DataTable rstData =   
                General.MyRst("SELECT ID, MineType, MyImage FROM Fighters WHERE ID = 4");  
    
            DataRow I = rstData.Rows[0];  
            Image1.ImageUrl = GetImage((byte[])I["MyImage"], (string)I["MineType"]);  
    
        }  
    
    
        string GetImage(byte[] MyImage, string MineType)  
        {  
            return $"Data:{MineType};base64,{Convert.ToBase64String(MyImage)}";  
        }  
    

    And the result is this:

    274202-image.png

    Now, in above, I did save in the database the "mine type". your example code did not, so you could pass the file name, and our routine would thus become this:

            DataRow I = rstData.Rows[0];  
            Image1.ImageUrl = GetImage((byte[])I["MyImage"], (string)I["FileName"]);  
    

    And the function now becomes this:

        string GetImage(byte[] MyImage, string sFile)  
        {  
            string sMineType = MimeMapping.GetMimeMapping(sFile);  
    
            return $"Data:{sMineType};base64,{Convert.ToBase64String(MyImage)}";  
        }  
    

    the really nice part about above? We can then even use this approach for display of images in a GridView.

    Regards,
    Albert D. Kallal (Access MVP 2003-2017)
    Edmonton, Alberta, Canada

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.