Question Problem Displaying Image From SQL Server

mattster6060

New member
Joined
Dec 15, 2011
Messages
2
Programming Experience
3-5
Afternoon,

I have an issue with the below vb.net code, its fails at the highlighted step below with 'Out Of Memory', can anybody shed any light as to why this is happening?

VB.NET:
  Try
            Dim da As SqlDataAdapter = New SqlDataAdapter()
            Dim cmd As SqlCommand
            Dim conn As New SqlConnection()
            conn.ConnectionString = "Data Source=******;Initial Catalog=****;User Id=****;Password=*****;"
            ' Create the SelectCommand.
            cmd = New SqlCommand("SELECT Employee.photo FROM Employee INNER JOIN Users ON Employee.Rn_Employee_User_Id = Users.Users_Id WHERE (Users.Login_Name = @User)", conn)
            cmd.Parameters.Add("@User", SqlDbType.NVarChar, 15)
            cmd.Parameters("@User").Value = user
            da.SelectCommand = cmd
            conn.Open()
            Dim barrImg As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
            Dim strfn As String = Convert.ToString(DateTime.Now.ToFileTime())
            Dim fs As New IO.FileStream(strfn, IO.FileMode.CreateNew, IO.FileAccess.Write)
            fs.Write(barrImg, 0, barrImg.Length)
            fs.Flush()
            fs.Close()
            [COLOR=#ff0000][B]Picturebox1.Image = Image.FromFile(strfn, False)
[/B][/COLOR]        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

Cheers,

Mattster
 
You don't need to, and in fact shouldn't, use a file to load the image.

Saving Images in Databases

If that doesn't work then I'd suggest that there's something wrong with the way you're saving the image in the first place. That same link can help you with that too.
 
Thanks jmcilhinney,

Ive amended my code as per below but get an invalid paramaeter on the below line:

VB.NET:
Dim connection As New SqlConnection("Data Source=***;Initial Catalog=****;User Id=**;Password=*****;")
        Dim command As New SqlCommand("SELECT Employee.photo FROM Employee INNER JOIN Users ON Employee.Rn_Employee_User_Id = Users.Users_Id WHERE (Users.Login_Name = '" + user + "')", connection)
        connection.Open()
        Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
        connection.Close()
        Dim picture As Image = Nothing
        'Create a stream in memory containing the bytes that comprise the image.
        Using stream As New IO.MemoryStream(pictureData)
            'Read the stream and create an Image object from the data.    
            [COLOR=#ff0000][B]picture = Image.FromStream(stream)
[/B][/COLOR]       End Using


I'll check how the image is placed in the database to see if this is causing a problem.
 
Back
Top