Reading a picture is much simpler than storing it. Output a picture all we have to do is use the BinaryWrite method of the Response object.
Format the picture at the same time. In this article, we'll discuss how to retrieve a picture from SQL Server. And will learn the following several aspects of knowledge.
• How do I format a picture?
• How to use the BinaryWrite method.
We've stored the data in the person table, so we write code to read the data from the table.
The following code retrieves all the values from the person table.
The code that reads the picture from SQL Server.
Public Sub Page_Load(sender As Object, e As EventArgs)
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("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
and see how he works?
The example above is very simple. All we do is execute an SQL statement and then loop through all the records (looping through all the records).
Before displaying the picture, we set the contenttype of the picture, and then we use the BinaryWrite method to output the picture to the browser.
Source:
Retriving.aspx
<%@ Page language= "vb"%>
<%@ Import namespace= "System.Data"%>
<%@ Import namespace= "System.Data.SqlClient"%>
<HTML>
<HEAD>
<title> retrieving Image from the SQL Server </title>
<script runat=server>
Public Sub Page_Load (sender as Object, E as EventArgs)
' Create Instance of Connection and Command Object
Dim MyConnection as New SqlConnection (ConfigurationSettings.AppSettings ("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
</script>
</HEAD>
<body style= "font:10pt Verdana"
</body>
</HTML>