How To Display an Image (binary data) from an Oracle9i Database in a Windows Forms PictureBox

Posted on 2006-05-18
Last Modified: 2012-05-05
I've tried many ways but can't find correct way.  The table description is:
ID_NMBR                                  NUMBER(9)
DTA_LNGTH                                NUMBER(4)
CPTRE_DTE                                DATE
SGNTRE                                   LONG RAW (yes we still using LONG RAW, and it's not going away)

Last piece of code I tried is:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim cn As New OracleConnection(ConnString)

        Dim cmd As New OracleCommand("SELECT ID_NMBR, " & _

        Dim da As New OracleDataAdapter(cmd)
        Dim ds As New DataSet

        Me.Label1.Text = cmd.ToString

        da.Fill(ds, "VO_SGNTRE")

        Dim c As Integer = ds.Tables("VO_SGNTRE").Rows.Count
        Me.Label1.Text = "Count: " & c.ToString
        If c > 0 Then
            Dim bytBLOBData() As Byte = _
                ds.Tables("VO_SGNTRE").Rows(c - 1)("SGNTRE")

            Dim stmBLOBData As New MemoryStream(bytBLOBData)

            picBLOB.Image = Image.FromStream(stmBLOBData)
        End If

    End Sub

                ERROR:    An unhandled exception of type 'System.ArgumentException' occurred in system.drawing.dll

                              Additional information: Invalid parameter used.

Thanks for your help.
Question by:soetal1
    LVL 5

    Expert Comment

    best advice.

    walk down to the database admin and shoot him for making you use oracle.
    LVL 11

    Expert Comment

    Are you sure the binary is a valid image?  Write it to disk using a binary writer give it an image extension and open it in a image viewer to make sure.  If the image was created using kofax you will need to remove the first 768 bytes of the binary, kofax adds it's own header to images and dotnet doesn't like it, open the image in a hext editor and check if there is a kofax header.  

                Dim bytePrintMe() As Byte = CType(myDatatable.Rows(0)("dp_page"), Byte())
                Dim myStream As New System.IO.MemoryStream(bytePrintMe)
                    imgPrintMe = System.Drawing.Image.FromStream(myStream)
                Catch ex As Exception
                    '-=- attempt to strip the first 768 bytes off
                    Dim byteTemp(bytePrintMe.Length - 768) As Byte
                    For intIdx As Integer = 768 To bytePrintMe.Length - 1
                        byteTemp(intIdx - 768) = bytePrintMe(intIdx)
                    Dim myNewStream As New System.IO.MemoryStream(byteTemp)
                    imgPrintMe = System.Drawing.Bitmap.FromStream(myNewStream)
                End Try

    And oracle is actually quite nice, not as nice as SQL Server perhaps but much bloody better than informix.

    Author Comment

    "walk down to the database admin and shoot him for making you use oracle."

    LordWabbit: Is "dp_page" table column name?
                       Is  imgPrintMe the image to be displayed?
    LVL 96

    Expert Comment

    by:Bob Learned
    1) When you get that error, it is because of a few reasons

       a) The data is not a supported image type
       b) You have incorrectly created the stream
    2) How are you storing the data in the BLOB?

    3) Yeah, somebody does sound like an Oracle hater.

    LVL 5

    Expert Comment

    If(oracleHater.Equals(DirectCast(Users("Mydasx"), User)))Then
    End If
    LVL 11

    Expert Comment

    yes dp_page is the column name in our database and imgPrintMe is the image being created to send to the printer which is declared locally and not shown in the code snippet.

    Author Comment

    LordWabbit, TheLearnedOne  thanks for your interest. Using BLOB types is very easy compared with LONG RAW types.
    Anyway it took me 4 days researching this matter and for the benefit of all members,  premium, or not I'll post the code.

    ----Don't know what to do with points. You may want to split them, or refund them. I'm happy I found the solution.
         Give myass... I mean mydasx 1 point because he wasn't that funny !

    ***************** INSERT a LONG RAW **********************************************

    Private Sub INSERT_ROW(ByVal strVoterID As Int32)
            Dim cmd As New OracleCommand
            Dim SQL As String
            Dim rawData() As Byte
            Dim fs As FileStream

                fs = New FileStream("C:\DTA\Images\sgntre.t", FileMode.Open, FileAccess.Read)
                rawData = New Byte(fs.Length) {}
                fs.Read(rawData, 0, fs.Length)

                cmd.Connection = OraConnect
                cmd.CommandText = SQL
                cmd.Parameters.Add("ID_NMBR", strVoterID)
                cmd.Parameters.Add("SGNTRE", rawData)
                Catch e As Exception
                End Try

                Me.txtEventLog.Text = Me.txtEventLog.Text & "File Inserted into database successfully!   " & strVoterID & vbCrLf
            Catch ex As Exception
                MessageBox.Show("There was an error: " & ex.Message, "Error", _
                                             MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

        End Sub

    ***************** READ/DISPLAY  LONG RAW **********************************************

    Private Sub RETRIEVE_IMAGE(ByVal strVoterID As Int32)
            Dim _strImageName As String = ""
            Dim _empID As String = ""
            Dim _curID As String = ""
            Dim _Length As Integer = 0

            '// For fetching read only rows from datasource
            Dim oraImgReader As OracleDataReader

            '// For executing SQL statements against datasource
            Dim oraImgCmd As OracleCommand

           ' // Reset variables
            _strImageName = ""
            _empID = ""

             oraImgCmd = New OracleCommand("SELECT ID_NMBR, SGNTRE FROM VO_SGNTRE " & _
                                "WHERE ID_NMBR = " & strVoterID, OraConnect)

            '// Set OracleConnection for this instance of OracleCommand
            oraImgCmd.Connection = OraConnect

            '// set InitialLONGFetchSize to a non-zero value
            oraImgCmd.InitialLONGFetchSize = 5000
            '// Set Command type as text
            oraImgCmd.CommandType = CommandType.Text

            '// Sends the CommandText to the Connection
            '// and builds an OracleDataReader
            oraImgReader = oraImgCmd.ExecuteReader()

            '// Read data
            '// Returns true if another row exists; otherwise, returns false.
            Dim recordExist As Boolean = oraImgReader.Read()

            '// If data exists
            If (recordExist) Then
                '// Store current Employee value
                If Not (oraImgReader.IsDBNull(0)) Then
                    '_curID = oraImgReader.GetInt32(0).ToString()
                    _curID = "ID not found"
                End If

                '// If Signatureo exists in the Database, load it into the PictureBox
                If (oraImgReader.GetValue(1).ToString() <> "") Then
                    '// Fetch the BLOB data through OracleDataReader using OracleBlob type
                    Dim blob As OracleBinary = oraImgReader.GetOracleBinary(1)

                    '// Create a byte array of the size of the Blob obtained
                    Dim byteArr As Byte() = New Byte(blob.Length) {}

                    '// Read blob data into byte array
                    Dim i As Long = oraImgReader.GetBytes(1, 0, byteArr, 0, blob.Length)
                    '// Get the primitive byte data into in-memory data stream
                    Dim memStream As MemoryStream = New MemoryStream(byteArr)

                    '// Attach the in-memory data stream to the PictureBox
                    Me.PictureBox1.Image = Image.FromStream(memStream)

                    '// Fit the image to the PictureBox size
                    Me.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
                    MessageBox.Show("1  SNTRE not found  " & oraImgReader.GetValue(2).ToString())
                End If

                '// close the OracleDataReader
            End If

            '// Catch exception when accessing arrary element out of bound
            Catch rangeException As System.IndexOutOfRangeException
                   MessageBox.Show("There was an error(rangeException)   : " & rangeException.Message, "Error", _
                                        MessageBoxButtons.OK, MessageBoxIcon.Error)

            Catch ex As Exception
            '// Display error message
                  MessageBox.Show("There was an error(ex)  : " & ex.Message, "Error", _
                                       MessageBoxButtons.OK, MessageBoxIcon.Error)

            End Try

        End Sub
    LVL 1

    Accepted Solution

    PAQed with points refunded (500)

    Community Support Moderator

    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Join & Write a Comment

    Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
    If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now