473,320 Members | 1,950 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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.
Nov 30 '11 #1
8 4475
Frinavale
9,735 Expert Mod 8TB
The web browser needs to access resources, like an image, using a URL.

For example:
Expand|Select|Wrap|Line Numbers
  1. <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
Expand|Select|Wrap|Line Numbers
  1. Public Partial Class Thumbnail
  2.   Inherits System.Web.UI.Page
  3.   Protected Sub Page_Load(sender As Object, e As EventArgs)
  4.  
  5.     'Changing the ContentType from HTML to image/jpg 
  6.     Response.ContentType = "image/jpg"
  7.  
  8.     'Retrieving the Image ID from the QuerytString
  9.     Dim id As As Integer
  10.     Integer.TryParse(Request.QueryString("ID"), id)
  11.  
  12.     'Connecting to the database and retrieving the image
  13.     'The connection string is stored in the web.config file...
  14.     Dim connectionString As String = ConfigurationManager.ConnectionStrings("ImageDatabaseConnectionString").ConnectionString
  15.  
  16.     Dim dbCon As SqlConnection
  17.     dbCon = New SqlConnection(connectionString) 
  18.     Dim sqlCom As New SqlCommand 
  19.     sqlCom.Connection = dbCon
  20.     sqlcom.CommandType = CommandType.Text
  21.     sqlCom.CommandText = "SELECT image FROM IMAGES " _ +
  22.                          "WHERE ID=@ImageID"
  23.     sqlCom.Parameters.Add("@ImageID", SqlDbType.Int).Value = id
  24.  
  25.     Try
  26.  
  27.       dbCon.Open()
  28.       Dim imgContents As Byte() = DirectCast(sqlcom.ExecuteScalar(), Byte())
  29.  
  30.       'Now that we have the image, writing it to the Response's Output Stream
  31.       Response.BinaryWrite(imgContents)
  32.  
  33.    Catch ex As Exception
  34.      'Something went wrong connecting to the Database
  35.    Finally
  36.      'Ensuring that the database connection is closed
  37.      'Even if something went wrong
  38.      dbCon.Close()
  39.    End Try               
  40.   End Sub
  41. 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 "ImageSource" 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:
Expand|Select|Wrap|Line Numbers
  1. <asp:Image ImageUrl="http://localhost/Thumbnail.aspx?id=4" />
-Frinny
Nov 30 '11 #2
Thank u so much.....
Dec 2 '11 #3
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.
Dec 2 '11 #4
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.
Expand|Select|Wrap|Line Numbers
  1.  
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Imports System.Data.Sql
  5. Imports System.IO
  6. Partial Class _Default
  7.     Inherits System.Web.UI.Page
  8.     Public cmd As SqlCommand
  9.     Public imgpath As String = ""
  10.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
  11.         'Changing the ContentType from HTML to image/jpg  
  12.         Response.ContentType = "image/jpg"
  13.  
  14.         'Retrieving the Image ID from the QuerytString 
  15.         Dim id As Integer = 1
  16.         Integer.TryParse(Request.QueryString("ID"), id)
  17.  
  18.         'Connecting to the database and retrieving the image 
  19.         'The connection string is stored in the web.config file... 
  20.         Dim connectionString As String = ConfigurationManager.ConnectionStrings("Data Source=localhost\sqlexpress;Initial Catalog=imagetsk;Integrated Security=True").ConnectionString
  21.  
  22.         Dim dbCon As SqlConnection
  23.         dbCon = New SqlConnection(connectionString)
  24.         Dim sqlCom As New SqlCommand
  25.         sqlCom.Connection = dbCon
  26.         sqlCom.CommandType = CommandType.Text
  27.         sqlCom.CommandText = "SELECT pics FROM imgestr " + "WHERE id=@ImageID"
  28.         sqlCom.Parameters.Add("@ImageID", SqlDbType.Int).Value = id
  29.  
  30.         Try
  31.  
  32.             dbCon.Open()
  33.             Dim imgContents As Byte() = DirectCast(sqlCom.ExecuteScalar(), Byte())
  34.  
  35.             'Now that we have the image, writing it to the Response's Output Stream 
  36.             Response.BinaryWrite(imgContents)
  37.  
  38.         Catch ex As Exception
  39.             'Something went wrong connecting to the Database 
  40.         Finally
  41.             'Ensuring that the database connection is closed 
  42.             'Even if something went wrong 
  43.             dbCon.Close()
  44.         End Try
  45.     End Sub
  46.  
  47.  
  48.  
  49.     Protected Sub Uploadbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Uploadbtn.Click
  50.         FileUpload1.SaveAs((Server.MapPath("pics").ToString() & "\") + FileUpload1.FileName)
  51.         Image1.ImageUrl = "~\pics\" + FileUpload1.FileName
  52.         cmd = New SqlCommand
  53.         Try
  54.             Using localcon As New SqlConnection("Data Source=localhost\sqlexpress;Initial Catalog=imagetsk;Integrated Security=True")
  55.                 localcon.Open()
  56.  
  57.                 cmd.Parameters.Add(New SqlParameter("@pics", SqlDbType.Image)).Value = IO.File.ReadAllBytes((Server.MapPath("pics").ToString() & "\") + FileUpload1.FileName)
  58.                 cmd.Connection = localcon
  59.                 cmd.CommandType = CommandType.Text
  60.                 cmd.CommandText = "insert into imgestr(pics,id) values(@pics,'" & ImgID.Text & "')"
  61.                 cmd.ExecuteNonQuery()
  62.                 MsgBox("Record is added")
  63.  
  64.                 ' End Using
  65.             End Using
  66.         Catch ex As Exception
  67.             MsgBox(ex.Message)
  68.         End Try
  69.     End Sub
  70.  
  71.     Protected Sub ImgID_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ImgID.TextChanged
  72.  
  73.     End Sub
  74. End Class
Dec 2 '11 #5
Frinavale
9,735 Expert Mod 8TB
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)
Dec 2 '11 #6
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
Dec 3 '11 #7
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...
Dec 3 '11 #8
Frinavale
9,735 Expert Mod 8TB
I'm glad it worked out for you :)
Dec 5 '11 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Bassem | last post by:
Hi all... I searhed for a code to save and retrieve image from SQL database using Data adapter but I didn't found anything. Thanks, Bassem.
2
by: oren18 | last post by:
hello.does anybody know .. how to make an image database by using VB.NET 2005 and Microsoft Access i want to make an application ( VB.NET 2005 ) that prompt a user to put his picture into...
0
by: oren18 | last post by:
hello.does anybody know .. how to make an image database by using VB.NET 2005 and Microsoft Access i want to make an application ( VB.NET 2005 ) that prompt a user to put his picture into...
0
by: shivavodnala | last post by:
retrieve image from sql server database when we click image button and it has to display on image control
0
by: PROGRAMMINGMAESTO | last post by:
How to Fetch and Retrieve image in ASP using MS Access. -------------------------------------------------------------------------------- Hello Friends, Can Anybody guide about how should i...
1
ganeshkumar08
by: ganeshkumar08 | last post by:
Hi all, Can i know how to retrieve the database which is deleted without knowing. I deleted one database, now i dont know how to retrieve it.. Can any one help me.. Thanks Ganesh
10
by: veenna | last post by:
How can i retrieve image files from a local system's My pictures folder and display those images?
0
by: newsco | last post by:
Dear all, I use VB6 ADO connect to Access 2007 accdb database, everything is fine except I cannot retrieve image file stored in the Access 2007 attachment data type. Can anyone show me some vb...
1
by: Mirazul Hasan | last post by:
I can store and retrieve image reference or location such as "E:\\New Folder\\Multipurpose\\image\\"+ txtname.Text + txtaccnumber.Text +".JPG"; . But I want to store original image and...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.