Search code examples
asp.netvisual-studio-2010sql-server-2012

How to retrieve an image from database and show it in asp image box with a click of a button?


private void ProcessedImage()
    {
        try
        {
            if (FileUpload1.HasFile)
            {

                int length = 192;
                int width = 192;

                using (Bitmap sourceImage = new Bitmap(FileUpload1.PostedFile.InputStream))
                {
                    using (Bitmap resizedImage = new Bitmap(length, width))
                    {
                        using (Graphics graphics = Graphics.FromImage(resizedImage))
                        {
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.SmoothingMode = SmoothingMode.HighQuality;
                            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                            graphics.DrawImage(sourceImage, 0, 0, length, width);
                        }

                        string resizedImagePath = Server.MapPath("~/Images/Image.png");
                        resizedImage.Save(resizedImagePath, ImageFormat.Png);

                        ImgPhoto.ImageUrl = "~/Images/Image.png";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string errorMessage = ("An error occurred " + ex.Message);
        }
    }

    public void Save()
        {
            try
            {
                byte[] imageData;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (Bitmap bitmap = new Bitmap(Server.MapPath("~/Images/finalImage.png")))
                    {
                        bitmap.Save(ms, ImageFormat.Png);
                        imageData = ms.ToArray();
                    }
                }
        
                using (SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=Karthik;User ID=admin;Password=admin"))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO image_tbl (ImageID,image_data) VALUES (@ImageID,@image_data)", con);
                    cmd.Parameters.AddWithValue("@ImageID", ImageID.Text.Trim());
                    cmd.Parameters.AddWithValue("@image_data", imageData);
                    cmd.ExecuteNonQuery();

                    Response.Write("<script>alert('Saved Succefully')</script>");
                }
            }
            catch (Exception ex)
            {
                string errorMessage = "An error occurred: " + ex.Message;
            }
        }

This is my code. I resized the image and saved it in the database. Now I want to take an input from the user for Image ID and retrieve the image corresponding to the image ID and show it in the asp text box. Is it possible to do so? Note that I am working in Visual Studio 2010. And I don't think it supports JavaScript codes.


Solution

  • Firstly, even vs2010 used lots of JavaScript, and in fact came with a Bootstrap main menu, had the JavaScript helper library jQuery installed.

    And in fact, your code even uses JavaScript here:

     Response.Write("<script>alert('Saved Successfully')</script>");
    

    To be clear, you have full use of JavaScript, and there are zero issues in regards to enjoying the use of JavaScript, and nothing stops you from using JavaScript.

    Now, having stated the above, there is no need to use JavaScript, and you don't have to write any JavaScript to solve your question. But, to be crystal clear, you have full use of JavaScript in your markup, and even projects created in vs2010 have FULL support for using JavaScript.

    Let's assume we have that saved image, as you note nice and small, and you want to show the preview.

    The only real issue is how many images you need to display on a page. This is because I going to post a very easy bit of code to display that image from the database, but this approach needs much caution, since we going to stream the image to the page as raw image bytes, and this approach means the "image" will travel back to the server when you click on a button, or ANY thing on that page that triggers a post-back (standard round trip) of the browser will "increase" the size and payload of this web page.

    For a smaller image or thumbnail type of image display, and only a few on the page, then this approach is acceptable, and easy to code.

    However, if there are to be many images, or the image is large, then I do NOT recommend this approach.

    As noted, since we only are to display one image, and since it is small, then we don't care. However, if your goal was to display MANY images on a page, then I do not recommend this approach for more then a few images displayed at the same time on a single page.

    I don't have your data, but this code shows how you can do this:

    I have a SQL Server table, and one of the columns is raw byte data of the saved image.

    The other issue is you need to know what file extension your picture was in the first place. For this example, it looks like .png, but if you are to allow different kinds of images, then you must save the file extension, or even better yet save the so called "mine" type of the image. This information allows us to tell the browser what kind of image we want to display.

    Let's say we fill a dropdown list with the rows of the database (without the column that holds the data).

    We have this markup:

            <h3>Select Fighter</h3>
            <asp:DropDownList ID="cboFighters" runat="server"
                DataValueField="ID"
                DataTextField="Fighter"
                AutoPostBack="true"
                OnSelectedIndexChanged="cboFighters_SelectedIndexChanged"
                Width="250px">
            </asp:DropDownList>
    
            <br />
    
    
            <div class="mybox" style="float: left">
                <div style="text-align: center; padding: 2px 10px 12px 10px">
    
                    <h3 id="Fighter" runat="server"></h3>
                    <asp:Image ID="Image2" runat="server"
                        Width="180" Height="120" />
    
                    <h4>Engine</h4>
                    <asp:Label ID="EngineLabel" runat="server" Text="" />
    
                    <h4>Description</h4>
                    <asp:Label ID="DescLabel" runat="server" Width="400px"
                        Text="" Style="text-align: left" Font-Size="Large" />
                </div>
            </div>
    

    Note that in the above, there is a image control.

    Now our code behind is this:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                cboFighters.DataSource =
                    General.MyRst("SELECT ID, Fighter FROM Fighters");
                cboFighters.DataBind();
                cboFighters.Items.Insert(0, new ListItem("Select Fighter", "0"));
            }
        }
    
        protected void cboFighters_SelectedIndexChanged(object sender, EventArgs e)
        {
    
            SqlCommand cmdSQL = 
                new SqlCommand("SELECT * FROM Fighters WHERE ID = @ID");
            cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = cboFighters.SelectedItem.Value;
    
            DataRow OneFighter = General.MyRstP(cmdSQL).Rows[0];
            Fighter.InnerText = OneFighter["Fighter"].ToString();
            EngineLabel.Text = OneFighter["Engine"].ToString();
            DescLabel.Text = OneFighter["Description"].ToString();
    
            string sMineType = OneFighter["MineType"].ToString();
            // stringSmineType = "image/png"  // hard coded value if all are .png
    
            byte[] MyBytePic = (byte[])OneFighter["MyImage"];
    
            Image2.ImageUrl = 
                $@"data:{sMineType};base64,{Convert.ToBase64String(MyBytePic)}";
    
        }
    

    And the result is this:

    enter image description here

    Note the use of "mine mapping". Quite sure that needs .net 4.5 or later.

    However, if all of your raw byte saved images in the database are .png, then you can hard code as the above commented out line shows.

    Note that the above same trick works if we fill out a gridview.

    However, as I stated, use some caution with this approach, since the image does not have any "real" URL path name to resolve, the browser will wind up sending the picture back to the server with each button click (and post back). Since there is no "real" URL, then the browser cannot cache such pictures. As noted, you can also consider creating a http handler, and they play much nicer then sending the picture as a base64 string.

    If you are concerned about keeping the page size small, or to leverage browser caching, then consider a custom picture handler.

    However, since in your case we have a small picture of 192x192, then the above approach is easy to code.