Reading images is much easier than storing images. To output an image, we must use the BinaryWrite method of the Response object.
Set the image format. In this article, we will discuss how to retrieve images from SqlServer. I will also learn the following knowledge.
· How to set the image format?
· How to Use the BinaryWrite method.
We have stored data in the Person table, so we will write some code to read data from the table.
The following code Retrieves all values from the Person table.
Code for reading images from sqlserver.
Public Sub Page_Load (sender As Object, e As EventArgs)
Dim myConnection As New SqlConnection (ConfigurationSettings. etettings ("ConnectionString "))
Dim myCommand As New SqlCommand ("Select * from Person", myConnection)
Try
MyConnection. Open ()
Dim myDataReader as SqlDataReader
MyDataReader = myCommand. ExecuteReader (CommandBehavior. CloseConnection)
Do While (myDataReader. Read ())
Response. ContentType = myDataReader. Item ("PersonImageType ")
Response. BinaryWrite (myDataReader. Item ("PersonImage "))
Loop
MyConnection. Close ()
Response. Write ("Person info successfully retrieved! ")
Catch SQLexc As SqlException
Response. Write ("Read Failed:" & SQLexc. ToString ())
End Try
End Sub
How does he work?
The example above is simple. What we do is to execute an SQL statement and read all records again (looping through all the records ).
Before displaying an image, we first set the contentType of the image, and then use the BinaryWrite method to output the image to the browser.
Source code:
/// Retriving. aspx
<% @ Page Language = "vb" %>
<% @ Import Namespace = "System. Data" %>
<% @ Import Namespace = "System. Data. SqlClient" %>