Monday, March 12, 2012

Retrieving Binary Image from SQL

i am trying to retrieve an image blob stored in SQL to a web matrix form (using VB.NET). I am totaly new to this and i got the code below from a site but it doesn't see to work....

<%@. Page Language="VB" %>

<%@. import Namespace="System.Data" %>

<%@. import Namespace="System.IO" %>

<%@. import Namespace="System.Drawing.Image" %>

<%@. import Namespace="System.Drawing.Bitmap" %>

<%@. import Namespace="System.Drawing.Graphics" %>

<%@. import Namespace="System.Web.UI.WebControls" %>

<%@. import Namespace="System.Data.Odbc" %>

<%@. import Namespace="System.Data.SqlClient" %>

<script runat="server">

Private Function GetImageFromDB(ByVal ImageID As Integer) As System.Drawing.Image

' Get the Connection string

Dim strConnection As String

strConnection = "server='(local)'; trusted_connection=true; database='mydatabasename'"

Dim conn As New SqlConnection(strConnection)

Dim sqlCommand As String

Dim strImage As String

Dim image As System.Drawing.Image

Try

sqlCommand = "SELECT ImageField FROM ImageTable WHERE MyImageId = " + ImageID.ToString

Dim cmd As New SqlCommand(sqlCommand)

cmd.Connection = conn

conn.Open()

Dim dr As SqlDataReader

dr = cmd.ExecuteReader()

While (dr.Read())

Dim byt As Byte()

byt = dr.Item(strImage)

Dim bmp As New System.Drawing.Bitmap(New System.IO.MemoryStream(byt))

image = bmp

End While

Catch ex As Exception

' Log Error

Response.Write(ex.Message)

Finally

If conn.State = ConnectionState.Open Then

conn.Close()

End If

End Try

Return image

End Function

Private Sub Page_Load (ByVal sender As System.Object, ByVal e As System.EventArgs)

If Not IsPostBack Then

GetImageFromDB(2111)

End If

End Sub

</script>

<html>

<head>

</head>

<body>

<form enctype="multipart/form-data" runat="server">

<asp:Image id="BrandSignImg" runat="server"></asp:Image>

</form></body></html>


You can not send two different content types with a single http request. ie Html and Image data.
You will need a HttpHandler for serving images out, or you can use a special .aspx page, here is a link to get your started.
http://www.sadeveloper.net/Forums/ShowPost.aspx?PostID=52636
bill

No comments:

Post a Comment