How to retrieve image from database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Akbar Abro
    New Member
    • Nov 2011
    • 13

    How to retrieve image from database

    Dear sir/Madam
    I am new in asp.net, tell me how can i retrieve image from database in asp.net through vb programming. And i have also uploaded a JPEG file in sql server 2005. So kindly tell me in an easy way...
    Thanks in advance
    regards,
    Akbar Abro.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    The web browser needs to access resources, like an image, using a URL.

    For example:
    Code:
    <asp:Image ImageUrl="http://localhost/myimage.jpg" />
    But since your image is stored in a database, there is no URL to the image.

    To get around this problem you should create an ASPX page that will retrieve the image from the database and return it (in it's binary form) to the browser instead of HTML (which is what the ASPX page would normally return).
    • Add an ASPX page called "Thumbnail.aspx " to your website for this purpose.
    • In the Page Load event:
      • Change the content-type that is part of "header" to indicate that you are returning an image
      • Retrieve the ID of the image from QueryString, Cookies, or Session (depending on how you are passing the ID of the image to this ASPX page)
      • Retrieve the image from the database and write that to the Response.Output stream

    Code:
    Public Partial Class Thumbnail
      Inherits System.Web.UI.Page
      Protected Sub Page_Load(sender As Object, e As EventArgs)
    
        'Changing the ContentType from HTML to image/jpg 
        Response.ContentType = "image/jpg"
    
        'Retrieving the Image ID from the QuerytString
        Dim id As As Integer
        Integer.TryParse(Request.QueryString("ID"), id)
    
        'Connecting to the database and retrieving the image
        'The connection string is stored in the web.config file...
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("ImageDatabaseConnectionString").ConnectionString
         
        Dim dbCon As SqlConnection
        dbCon = New SqlConnection(connectionString) 
        Dim sqlCom As New SqlCommand 
        sqlCom.Connection = dbCon
        sqlcom.CommandType = CommandType.Text
        sqlCom.CommandText = "SELECT image FROM IMAGES " _ +
                             "WHERE ID=@ImageID"
        sqlCom.Parameters.Add("@ImageID", SqlDbType.Int).Value = id
    
        Try
         
          dbCon.Open()
          Dim imgContents As Byte() = DirectCast(sqlcom.ExecuteScalar(), Byte())
         
          'Now that we have the image, writing it to the Response's Output Stream
          Response.BinaryWrite(imgContents)
    
       Catch ex As Exception
         'Something went wrong connecting to the Database
       Finally
         'Ensuring that the database connection is closed
         'Even if something went wrong
         dbCon.Close()
       End Try   			
      End Sub
    End Class
    So now you have an ASPX page that returns an image in the form of a Byte Array to the browser.

    You can now use the URL to this page as the "ImageSourc e" of an ASP.NET Image control to display the Image that is returned. All you have to do is make sure to pass the ID of the image you want to retrieve through the query string using the URL (because that's what this example is using...but you could use Session or Cookies or whatever you please)

    Like this:
    Code:
    <asp:Image ImageUrl="http://localhost/Thumbnail.aspx?id=4" />
    -Frinny
    Last edited by Frinavale; Nov 30 '11, 07:35 PM.

    Comment

    • Akbar Abro
      New Member
      • Nov 2011
      • 13

      #3
      Thank u so much.....

      Comment

      • Akbar Abro
        New Member
        • Nov 2011
        • 13

        #4
        sir i have written the complete programe. so plz now tell me where should i use this script <asp:Image ImageUrl="http://localhost/Thumbnail.aspx? id=4" />
        still i am getting problem to retrieve the image from database.
        Last edited by Frinavale; Dec 2 '11, 09:35 PM. Reason: Added code tags

        Comment

        • Akbar Abro
          New Member
          • Nov 2011
          • 13

          #5
          Sir I have written the complete program.

          So please now tell me where should i use this script <asp:Image ImageUrl="http://localhost/Thumbnail.aspx? id=4" />

          Still I am getting problem to retrieve the image from database.
          Code:
          Imports System.Data
          Imports System.Data.SqlClient
          Imports System.Data.Sql
          Imports System.IO
          Partial Class _Default
              Inherits System.Web.UI.Page
              Public cmd As SqlCommand
              Public imgpath As String = ""
              Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
                  'Changing the ContentType from HTML to image/jpg  
                  Response.ContentType = "image/jpg"
          
                  'Retrieving the Image ID from the QuerytString 
                  Dim id As Integer = 1
                  Integer.TryParse(Request.QueryString("ID"), id)
          
                  'Connecting to the database and retrieving the image 
                  'The connection string is stored in the web.config file... 
                  Dim connectionString As String = ConfigurationManager.ConnectionStrings("Data Source=localhost\sqlexpress;Initial Catalog=imagetsk;Integrated Security=True").ConnectionString
          
                  Dim dbCon As SqlConnection
                  dbCon = New SqlConnection(connectionString)
                  Dim sqlCom As New SqlCommand
                  sqlCom.Connection = dbCon
                  sqlCom.CommandType = CommandType.Text
                  sqlCom.CommandText = "SELECT pics FROM imgestr " + "WHERE id=@ImageID"
                  sqlCom.Parameters.Add("@ImageID", SqlDbType.Int).Value = id
          
                  Try
          
                      dbCon.Open()
                      Dim imgContents As Byte() = DirectCast(sqlCom.ExecuteScalar(), Byte())
          
                      'Now that we have the image, writing it to the Response's Output Stream 
                      Response.BinaryWrite(imgContents)
          
                  Catch ex As Exception
                      'Something went wrong connecting to the Database 
                  Finally
                      'Ensuring that the database connection is closed 
                      'Even if something went wrong 
                      dbCon.Close()
                  End Try
              End Sub
          
             
          
              Protected Sub Uploadbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Uploadbtn.Click
                  FileUpload1.SaveAs((Server.MapPath("pics").ToString() & "\") + FileUpload1.FileName)
                  Image1.ImageUrl = "~\pics\" + FileUpload1.FileName
                  cmd = New SqlCommand
                  Try
                      Using localcon As New SqlConnection("Data Source=localhost\sqlexpress;Initial Catalog=imagetsk;Integrated Security=True")
                          localcon.Open()
          
                          cmd.Parameters.Add(New SqlParameter("@pics", SqlDbType.Image)).Value = IO.File.ReadAllBytes((Server.MapPath("pics").ToString() & "\") + FileUpload1.FileName)
                          cmd.Connection = localcon
                          cmd.CommandType = CommandType.Text
                          cmd.CommandText = "insert into imgestr(pics,id) values(@pics,'" & ImgID.Text & "')"
                          cmd.ExecuteNonQuery()
                          MsgBox("Record is added")
          
                          ' End Using
                      End Using
                  Catch ex As Exception
                      MsgBox(ex.Message)
                  End Try
              End Sub
          
              Protected Sub ImgID_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ImgID.TextChanged
          
              End Sub
          End Class
          Last edited by Frinavale; Dec 2 '11, 09:34 PM. Reason: Added code tags and changed text-speak into proper English.

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            The purpose of the Thumbnail.aspx page is to provide a URL for an Image control to link to (and of course it retrieves the image from the database and sends it to the browser).

            So the Thubnail.aspx page is part of your application.

            Back in the page that you were originally work with...the one where you need to display the image...

            That is where you put the <asp:Image ImageUrl="http://localhost/Thumbnail.aspx? id=4" />

            (I hope you realize that you have to provide a valid ID instead of the number "4" in order for this to work in your application)
            Last edited by Frinavale; Dec 2 '11, 09:40 PM.

            Comment

            • Akbar Abro
              New Member
              • Nov 2011
              • 13

              #7
              sir i have provided in source ..... but still its not working.. let me tell the usage of this script....i have use this script as a Url of image control...but its not functioning<asp :Image ImageUrl="http://localhost/Thumbnail.aspx? id=4" />
              plz help me

              Comment

              • Akbar Abro
                New Member
                • Nov 2011
                • 13

                #8
                yeah i have done it.. and now rightly understand the problem... thank u sir for this anticipation... . i love this forum. i was worry about it.. now my problem has been solved by the kind of u...

                Comment

                • Frinavale
                  Recognized Expert Expert
                  • Oct 2006
                  • 9749

                  #9
                  I'm glad it worked out for you :)

                  Comment

                  Working...