How to display image from the database?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AnagJohari
    New Member
    • May 2010
    • 96

    How to display image from the database?

    I would like to of display an the image at a proper position on a browser. I access the image from the database before doing this I stored the image in a database in a byte form. I also make a functionality of add image in a database.

    When i retrieve the image from the database onliy image is displayed on a browser . The form from which I add the image is not displayed.

    This is the aspx page coding
    Code:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ins_Image_in_DB.aspx.cs" Inherits="ImageDemo" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
    <h1>Insert Image In Database</h1>
        <div id="dv_visible" runat="server">    
        <form id="form1" runat="server" method="post">
        <div>
        <table border="3" cellspacing="3" width="300px">
        <tr>
        <td>
        <b>Image_Name</b>
        </td>
        <td>
        <asp:TextBox ID="txtImageName" runat="server" ></asp:TextBox>
      </td>
     </tr>
         <tr><td>
         <b>ImageUpload</b>
         </td>
         <td>
        <asp:FileUpload ID="UploadImage" runat="server" />
        </td>
        </tr>
        <tr>
        <td colspan="2" align="right">
        <asp:Button ID="AddImage" runat="server" Text="InsertImage" Font-Bold="true" 
                onclick="AddImage_Click"/>
        </td>
         </tr>
        </table>
        <asp:Label ID="Message" runat="server"></asp:Label>
        </div><h1>Select Image</h1>
        <asp:DropDownList ID="ddlImageDisplay" runat="server" AutoPostBack="True"></asp:DropDownList>
        
       
        </form>
        </div>
    
        <div>
        <asp:Image ID="DisplayImage" runat="server" ImageUrl="Ins_Image_in_DB.aspx" />
       <%--  <img src="Ins_Image_in_DB.aspx" alt="image not dispalyed"/>--%>
        </div>
        
    
        
        </body>
    </html>
    That is the .cs page coding
    Code:
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.IO;
    using System.Collections.Generic;
    using BllDummy;
    
    public partial class ImageDemo : System.Web.UI.Page
    {
        DummyBLL dummy = new DummyBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            dv_visible.Visible = true;
    
            if (!Page.IsPostBack)
            {
                dropdownImagelist();
            }
           selectedImagedisplay();
    
        }
        protected void AddImage_Click(object sender, EventArgs e)
        {
             Stream imgStream = UploadImage.PostedFile.InputStream;
             int ImgLength= UploadImage.PostedFile.ContentLength;
             dummy.ImageName = txtImageName.Text;
             dummy.ImageContentType = UploadImage.PostedFile.ContentType;
             byte[] imageType = new byte[ImgLength];
             dummy.ImageType = imageType;
             int n = imgStream.Read(imageType, 0, ImgLength);
             int roweffected= dummy.addImage();
             if (n >= 0)
                 Message.Text = "Image Is Saved In a database";
             else
                 Message.Text = "error Occur";
            
        }
        private void dropdownImagelist()
       {
            List<DummyBLL> ListImages = dummy.DisplayImage();
            ddlImageDisplay.Items.Add(new ListItem("--SelectImage---", "0"));
            foreach (DummyBLL ImageObject in ListImages)
            {
                ddlImageDisplay.Items.Add(new ListItem(ImageObject.ImageName.ToString(), ImageObject.ImageId.ToString()));
    
    
            }
        }
            private void selectedImagedisplay()
            {
                List<DummyBLL> ListImages = dummy.DisplayImage();
                foreach (DummyBLL ImageObject in ListImages)
                {
                    if (ImageObject.ImageId.ToString() == ddlImageDisplay.SelectedValue)
                    {
                        dummy.ImageId = ImageObject.ImageId;
                        dummy = dummy.displayImage();
                        Response.ContentType = dummy.ImageContentType;
                        Response.BinaryWrite(dummy.ImageType);
    
                        break;
                    }
                }
    
    
        }
    
    
    
    
    
    }
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    The reason only the image is showing up is because you are writing it to the Response output stream.

    You have the right idea here....but you want to move this code into an ASPX page of its own. This page will retrieve the image from the database and write it to the response output stream. (You'll have to change the header content type to be "image")

    So you have a ASPX page that will return binary-image content instead of HTML (which is what's normally returned).

    To display this in a particular place you will use an Image control. Set the Image control's source so that it calls the ASPX page that returns the image.

    The thing is that you will need to specify the ID of the image using the URL :)

    So you have something like this....


    An ASPX page, called "Thumbnail" , that will serve the image to the browser (the actual asp code for this doesn't matter because it's going to be over written when you write the image to the Response output stream...this is the C# code responsible for that):
    Code:
    public partial class Thumbnail : System.Web.UI.Page
    {
            protected void Page_Load(object sender, EventArgs e)
            {
                Response.ContentType = "image/jpg";
                string id = Request.QueryString("ID");
                selectedImageDisplay(id);
            }
    
            private void selectedImageDisplay(string id)
            {
                List<DummyBLL> ListImages = dummy.DisplayImage();
                foreach (DummyBLL ImageObject in ListImages)
                {
                    if (ImageObject.ImageId.ToString() == id)
                    {
                        dummy.ImageId = ImageObject.ImageId;
                        dummy = dummy.displayImage();
                        Response.ContentType = dummy.ImageContentType;
                        Response.BinaryWrite(dummy.ImageType);
     
                        break;
                    }
                }
            }
    }
    Now, back in your ImageDemo ASPX page you would have something like the following (notice at the bottom how I added an Image control):
    Code:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ins_Image_in_DB.aspx.cs" Inherits="ImageDemo" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
    <h1>Insert Image In Database</h1>
        <div id="dv_visible" runat="server">    
        <form id="form1" runat="server" method="post">
        <div>
        <table border="3" cellspacing="3" width="300px">
        <tr>
        <td>
        <b>Image_Name</b>
        </td>
        <td>
        <asp:TextBox ID="txtImageName" runat="server" ></asp:TextBox>
      </td>
     </tr>
         <tr><td>
         <b>ImageUpload</b>
         </td>
         <td>
        <asp:FileUpload ID="UploadImage" runat="server" />
        </td>
        </tr>
        <tr>
        <td colspan="2" align="right">
        <asp:Button ID="AddImage" runat="server" Text="InsertImage" Font-Bold="true" 
                onclick="AddImage_Click"/>
        </td>
         </tr>
        </table>
        <asp:Label ID="Message" runat="server"></asp:Label>
        </div><h1>Select Image</h1>
        <asp:DropDownList ID="ddlImageDisplay" runat="server" AutoPostBack="True"></asp:DropDownList>
    
    
    <asp:Image ID="DummyBLLImage" runat="server" />
     
        </form>
        </div>
    And in your ImageDemo's C# code...change the selectedImagedi splay method to provide the ImageUrl source for the new Image control...havin g it point to the Thumbnail.aspx page that provides the binary-image to the Image control:
    Code:
    private void selectedImagedisplay()
    {
      string id =  ddlImageDisplay.SelectedValue;
      DummyBLLImage.ImageUrl = "~/Thumbnail.aspx?id="+id;
    }
    -Frinny

    Comment

    • AnagJohari
      New Member
      • May 2010
      • 96

      #3
      Originally posted by Frinavale
      The reason only the image is showing up is because you are writing it to the Response output stream.

      You have the right idea here....but you want to move this code into an ASPX page of its own. This page will retrieve the image from the database and write it to the response output stream. (You'll have to change the header content type to be "image")

      So you have a ASPX page that will return binary-image content instead of HTML (which is what's normally returned).

      To display this in a particular place you will use an Image control. Set the Image control's source so that it calls the ASPX page that returns the image.

      The thing is that you will need to specify the ID of the image using the URL :)

      So you have something like this....


      An ASPX page, called "Thumbnail" , that will serve the image to the browser (the actual asp code for this doesn't matter because it's going to be over written when you write the image to the Response output stream...this is the C# code responsible for that):
      Code:
      public partial class Thumbnail : System.Web.UI.Page
      {
              protected void Page_Load(object sender, EventArgs e)
              {
                  Response.ContentType = "image/jpg";
                  string id = Request.QueryString("ID")
                  selectedImageDisplay(id);
              }
      
              private void selectedImageDisplay(string id)
              {
                  List<DummyBLL> ListImages = dummy.DisplayImage();
                  foreach (DummyBLL ImageObject in ListImages)
                  {
                      if (ImageObject.ImageId.ToString() == id)
                      {
                          dummy.ImageId = ImageObject.ImageId;
                          dummy = dummy.displayImage();
                          Response.ContentType = dummy.ImageContentType;
                          Response.BinaryWrite(dummy.ImageType);
       
                          break;
                      }
                  }
              }
      }
      Now, back in your ImageDemo ASPX page you would have something like the following (notice at the bottom how I added an Image control):
      Code:
      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ins_Image_in_DB.aspx.cs" Inherits="ImageDemo" %>
       
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
       
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title>Untitled Page</title>
      </head>
      <body>
      <h1>Insert Image In Database</h1>
          <div id="dv_visible" runat="server">    
          <form id="form1" runat="server" method="post">
          <div>
          <table border="3" cellspacing="3" width="300px">
          <tr>
          <td>
          <b>Image_Name</b>
          </td>
          <td>
          <asp:TextBox ID="txtImageName" runat="server" ></asp:TextBox>
        </td>
       </tr>
           <tr><td>
           <b>ImageUpload</b>
           </td>
           <td>
          <asp:FileUpload ID="UploadImage" runat="server" />
          </td>
          </tr>
          <tr>
          <td colspan="2" align="right">
          <asp:Button ID="AddImage" runat="server" Text="InsertImage" Font-Bold="true" 
                  onclick="AddImage_Click"/>
          </td>
           </tr>
          </table>
          <asp:Label ID="Message" runat="server"></asp:Label>
          </div><h1>Select Image</h1>
          <asp:DropDownList ID="ddlImageDisplay" runat="server" AutoPostBack="True"></asp:DropDownList>
      
      
      <asp:Image ID="DummyBLLImage" runat="server" />
       
          </form>
          </div>
      And in your ImageDemo's C# code...change the selectedImagedi splay method to provide the ImageUrl source for the new Image control...havin g it point to the Thumbnail.aspx page that provides the binary-image to the Image control:
      Code:
      private void selectedImagedisplay()
      {
        string id =  ddlImageDisplay.SelectedValue;
        DummyBLLImage.ImageUrl = "~/Thumbnail.aspx?id="+id;
      }
      -Frinny
      Actually i have little problem to understand this
      by the in a Selected Display method you Pass a url in imageurl property
      But in a ImageUrl field we pass the path of image at which the image is saved so that it display the image at image control
      But you Pass that url on which image is not saved.
      I confused at this thing.

      what i got from ur code i try to describe.
      By the way you forget to call the seletedimage display method ,
      first we have to call this method , after that you access the id from the query string....
      & pass this id to another selectedImagedi splay(id)
      So the image is retrieved from that method....

      little confused here

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Hmm...I'm confused about what you're confused about.
        I don't know the details of your BLLDummy class so I'm not sure how it works. I based the example code off of your posted code since I have no database with pictures in it or class that retrieves them to work with.

        Here on the basic details on what I was trying to get at.
        • You need to retrieve the image from the database when an <img> HTML tag requests it (ASP.NET Image controls are rendered as <img> HTML). The only way that the <img> tag can get the image is for it to request the image.
        • Create a "Thumbnail.aspx " page that the <img> tag can call to retrieve the picture.
        • In order to retrieve the correct image we must tell the Thumbnail.aspx page which image to retrieve. To do that we pass the "id" of where to locate the "image" using the URL. This way you can set the <img src="Thumbnail. aspx?id=theIdOf TheImage" />. You can dynamically set this by setting the Image.ImageUrl = "~/Thumbnail.aspx? id=theIdOfTheIm age".
        • The Thumbnail.aspx page contains all the code necessary to retrieve the image....that's all it does.


        -Frinny

        Comment

        • AnagJohari
          New Member
          • May 2010
          • 96

          #5
          Originally posted by Frinavale
          Hmm...I'm confused about what you're confused about.
          I don't know the details of your BLLDummy class so I'm not sure how it works. I based the example code off of your posted code since I have no database with pictures in it or class that retrieves them to work with.

          Here on the basic details on what I was trying to get at.
          • You need to retrieve the image from the database when an <img> HTML tag requests it (ASP.NET Image controls are rendered as <img> HTML). The only way that the <img> tag can get the image is for it to request the image.
          • Create a "Thumbnail.aspx " page that the <img> tag can call to retrieve the picture.
          • In order to retrieve the correct image we must tell the Thumbnail.aspx page which image to retrieve. To do that we pass the "id" of where to locate the "image" using the URL. This way you can set the <img src="Thumbnail. aspx?id=theIdOf TheImage" />. You can dynamically set this by setting the Image.ImageUrl = "~/Thumbnail.aspx? id=theIdOfTheIm age".
          • The Thumbnail.aspx page contains all the code necessary to retrieve the image....that's all it does.


          -Frinny
          Sorry for late reply i was too much busy these days..........
          let me renind you that i have a problem to display the image in asp image control...

          what actually happiened
          Code:
           Response.ContentType = dummy.ImageContentType;
           Response.BinaryWrite(dummy.ImageType);
          the above just display the image according to its actual size.
          the code
          Code:
          DisplayImage.ImageUrl = "~/Ins_Image_in_DB.aspx?Imageid=" + identity;
          so that still i m not able to put image at image control.
          even i use this statement.after bineray.write statement.
          i send my code please check it.......
          Code:
          using System;
          using System.Collections;
          using System.Configuration;
          using System.Data;
          using System.Linq;
          using System.Web;
          using System.Web.Security;
          using System.Web.UI;
          using System.Web.UI.HtmlControls;
          using System.Web.UI.WebControls;
          using System.Web.UI.WebControls.WebParts;
          using System.Xml.Linq;
          using System.IO;
          using System.Collections.Generic;
          using BllDummy;
          using System.Drawing;
          
          public partial class ImageDemo : System.Web.UI.Page
          {
              DummyBLL dummy = new DummyBLL();
              protected void Page_Load(object sender, EventArgs e)
              {
                  dv_visible.Visible = true;
          
                  if (!Page.IsPostBack)
                  {
                      dropdownImagelist();
                      
                  }
                  selectedImagedisplay();
                 
              
                 
          
              }
              protected void AddImage_Click(object sender, EventArgs e)
              {
                  Stream imgStream = UploadImage.PostedFile.InputStream;
                  int ImgLength = UploadImage.PostedFile.ContentLength;
                  dummy.ImageName = txtImageName.Text;
                  dummy.ImageContentType = UploadImage.PostedFile.ContentType;
                  byte[] imageType = new byte[ImgLength];
                  dummy.ImageType = imageType;
                  int n = imgStream.Read(imageType, 0, ImgLength);
                  int roweffected = dummy.addImage();
                  if (n >= 0)
                      Message.Text = "Image Is Saved In a database";
                  else
                      Message.Text = "error Occur";
                  selectedImagedisplay();
          
          
              }
              private void dropdownImagelist()
              {
                  List<DummyBLL> ListImages = dummy.DisplayImage();
                  ddlImageDisplay.Items.Add(new ListItem("--SelectImage---", "0"));
                  foreach (DummyBLL ImageObject in ListImages)
                  {
                      ddlImageDisplay.Items.Add(new ListItem(ImageObject.ImageName.ToString(), ImageObject.ImageId.ToString()));
          
          
                  }
              }
              private void selectedImagedisplay()
              {
                  List<DummyBLL> ListImages = dummy.DisplayImage();
                  Table table = new Table();
                  TableRow tablerow = new TableRow();
                  foreach (DummyBLL ImageObject in ListImages)
                  {
                      /*if (ImageObject.ImageId.ToString() == ddlImageDisplay.SelectedValue)
                       {
                           dummy.ImageId = ImageObject.ImageId;
                           dummy = dummy.displayImage();
                           Response.ContentType = dummy.ImageContentType;
                           Response.BinaryWrite(dummy.mageType);
          
                           break;
                       }*/
          
          
          
          
                      TableCell cell = new TableCell();
                      cell.ForeColor = System.Drawing.Color.Chocolate;
                      cell.BackColor = System.Drawing.Color.LemonChiffon;
          
          
                      LinkButton ImageLink = new LinkButton();
                      ImageLink.ID = ImageObject.ImageId.ToString();
                      ImageLink.Text = ImageObject.ImageName;
                      ImageLink.CommandArgument = ImageObject.ImageId.ToString();
                      ImageLink.CommandName = ImageObject.ImageId.ToString();
                      ImageLink.Command += new CommandEventHandler(btnImage_Click);
                      cell.Controls.Add(ImageLink);
          
                      tablerow.Cells.Add(cell);
          
          
          
          
                  }
                  table.Rows.Add(tablerow);
                  panelImage.Controls.Add(table);
              }
              protected void btnImage_Click(object sender, CommandEventArgs e)
              {
          
                  List<DummyBLL> ListImages = dummy.DisplayImage();
                  foreach (DummyBLL ImageObject in ListImages)
                  {
                      if (e.CommandName == ImageObject.ImageId.ToString())
                      {
                          int id = Convert.ToInt32(e.CommandArgument.ToString());
                          dummy.ImageId = id;
                          string identity=id.ToString();
                          dummy = dummy.displayImage();
                          DisplayImage.ImageUrl = "~/Ins_Image_in_DB.aspx?Imageid=" + identity;
                          Response.ContentType = dummy.ImageContentType;
                          Response.BinaryWrite(dummy.ImageType);
                          
                          lblmess.Text = identity;
                          break;
                      }
          
          
                  }
              }
              
          }
          The image is displayed with its original size.
          while i set the width & height of image in image control
          but this property is not applied.
          Thank You.......

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            You have to move the code that writes the image to the Response into another aspx page...It looks like you are going to call that page "Ins_Image_in_D B"....I would have called it "Thumbnail" .

            -Frinny

            Comment

            • AnagJohari
              New Member
              • May 2010
              • 96

              #7
              Originally posted by Frinavale
              You have to move the code that writes the image to the Response into another aspx page...It looks like you are going to call that page "Ins_Image_in_D B"....I would have called it "Thumbnail" .

              -Frinny
              I will exaplain what i do......
              I crette a "Ins_Image_in_D B".aspx page ok.
              after that i add a image control to this aspx page.
              when i retrieve the image from the database . i doesnot use the image control just retrieve the image from the database & display the image by using binary.write .
              in its orginal size.
              why we can't do here in this page.

              Comment

              • Christopher Nigro
                New Member
                • Jul 2010
                • 53

                #8
                Hi AnagJohari,

                You keep saying the same thing over and over - try to listen to what Frinny is saying. He is describing a method that I have used many times so I can attest that it is the proper way to do it.

                The aspx page that is responsible for rendering the image is to have NO MARKUP AT ALL except for the page directive. DO NOT add an image control to this page! Its code-behind will retrieve the image from the database based on an image ID that you can retrieve from the querystring and write it to the response stream.

                Add the image control to the page that is to display the image and set its image URL to the page that we were talking about in the previous paragraph. The url should also have a querystring variable with the ID of the image that you want to show.

                Comment

                • AnagJohari
                  New Member
                  • May 2010
                  • 96

                  #9
                  Tnx frinny you are great man. now i get my image at a right place..
                  tnx critopher nitro your comments also helps me to comeout from my situation......

                  Ok i done this
                  but try to understand this concept
                  i m very new .net i just finish my study so sometime what did u say not able to get easily.
                  so sorry for this
                  i want to clear this concept
                  when i call image control on image_insert_in Db not get
                  when i transfer my code in thumpsnail its work plz
                  little explain this....

                  Comment

                  Working...