asp.netvb.net

Save Image directly to Database from Asp Image Control


I displayed an barcode from httphandler to Asp: Image control, Now I want to save image to Database image field. I used below code to generate Barcode and diplay it in Image1 control

 Dim src As String = "https://barcode.tec-it.com/barcode.ashx?data=" + txtNewPPO.Text + "  &code=Code128&translate-esc=on'/>"
    Image1.ImageUrl = src

Now I treid to save by using below code:

 Dim imgPath As String = Image1.ImageUrl
 Dim pic As Byte() = ReadFile(imgpath)
 Dim qry1 As String = "Insert Into Employees (EmpID, EmpBarCode)values (@id,@img)"
 Dim myCommand As New SqlCommand(qry1, CN)
        myCommand.Parameters.Add(New SqlParameter("id", SqlDbType.VarChar)).Value = Me.txtNewPPO.Text
        myCommand.Parameters.Add(New SqlParameter("img", SqlDbType.Image)).Value = pic
CN.Open()
        myCommand.ExecuteNonQuery()
        CN.Close()

To Convert Image to Byte array i used the below method;

Public Function ReadFile(ByVal sPath As String) As Byte()

    Dim data As Byte() = Nothing
    Dim fInfo As FileInfo = New FileInfo(sPath)
    Dim numBytes As Long = fInfo.Length
    Dim fStream As FileStream = New FileStream(sPath, FileMode.Open, FileAccess.Read)
    Dim br As BinaryReader = New BinaryReader(fStream)
    data = br.ReadBytes(CInt(numBytes))
    fStream.Close()
    fStream.Dispose()
    Return data
End Function

But is showing an error with illegal file path etc.


Solution

  • Ok, you have a image control, and a image URL.

    You have to first "download" the image, convert to a byte array, and then save to the database.

    Hence, to save the image, then this code:

        Protected Sub cmdSave_Click(sender As Object, e As EventArgs)
    
    
            Dim iBytes As Byte()        ' holds our download image
    
            Dim MyWebClient As New WebClient
            iBytes = MyWebClient.DownloadData(Image1.ImageUrl)  ' get image as byte array
    
            ' get PoNum - assume text after "data="
            Dim sDelim As String() = New String() {"data="}
            Dim sPoNum As String = Image1.ImageUrl.Split(sDelim, StringSplitOptions.None)(1)
    
    
            Dim strSQL As String =
                "INSERT INTO tblBarCodes (PoNum, BImage)
                VALUES (@PoNum, @BImage)"
    
            Dim cmdSQL As New SqlCommand(strSQL)
            cmdSQL.Parameters.Add("@PoNum", SqlDbType.NVarChar).Value = sPoNum
            cmdSQL.Parameters.Add("@BImage", SqlDbType.VarBinary).Value = iBytes
    
            MyRstPE(cmdSQL)
    
        End Sub
    
    So, in above, I assumed the PoNum is part of the URL.
    
    Then, code to load the image from the database?
    
    This:
    
        Protected Sub cmdLoadFromDB_Click(sender As Object, e As EventArgs)
    
            Dim iBytes As New Byte()
    
            Dim strSQL As String =
                "SELECT * FROM tblBarCodes WHERE POnum = @PoNum"
            Dim cmdSQL As New SqlCommand(strSQL)
            cmdSQL.Parameters.Add("@PoNum", SqlDbType.NVarChar).Value = TextBox1.Text
            Dim dtBarCode As DataTable = MyRstP(cmdSQL)
    
            If dtBarCode.Rows.Count > 0 Then
    
                Dim sMineType As String = System.Web.MimeMapping.GetMimeMapping(".gif")
    
                Dim sImageas64 As String =
                    $"data:{sMineType};base64,{Convert.ToBase64String(dtBarCode.Rows(0)("BImage"))}"
    
    
                Image2.ImageUrl = sImageas64
    
    
            End If
    
        End Sub
    
    
    So, say some test code like this to load a test bar code:
    
                <asp:Button ID="cmdLoadImage" runat="server" Text="Load Image"
                    CssClass="btn"
                    OnClick="cmdLoadImage_Click"
                    />
    
                <br />
                <br />
                <br />
    
                <asp:Image ID="Image1" runat="server" />
    
                <br />
    
    Code behind:
    
        Protected Sub cmdLoadImage_Click(sender As Object, e As EventArgs) Handles cmdLoadImage.Click
    
            Image1.ImageUrl = "https://barcode.tec-it.com/barcode.ashx?data=1234"
    
        End Sub
    
    Result:
    

    enter image description here

    So, above loads the image (it is of type .gif).

    So, after running code to save the image to the database. Then test code above to load the image is thus:

    enter image description here

    While not too important, the 2nd markup is this:

                <h3>test load image from database</h3>
                Enter PO num:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <br />
                <asp:Button ID="cmdLoadFromDB" runat="server" Text="Load Image from database"
                    CssClass="btn"
                    OnClick="cmdLoadFromDB_Click"
                    />
                <br />
                <asp:Image ID="Image2" runat="server" />
    

    And of course, one fast becomes REALLY tired of typing connection code over and over, so I have in my general code module this global helper routine:

        Public Sub MyRstPE(cmdSQL As SqlCommand)
            ' general execute sql - no return of data
    
            Dim rstData As New DataTable
            Using conn As New SqlConnection(GetConStr)
                Using (cmdSQL)
                    cmdSQL.Connection = conn
                    conn.Open()
                    cmdSQL.ExecuteNonQuery()
                End Using
            End Using
    
        End Sub
    

    And

        Public Function MyRstP(cmdSQL As SqlCommand) As DataTable
            ' general get any data from SQL command
            dim strCon as string = GetConStr()
    
            Dim rstData As New DataTable
            Using conn As New SqlConnection(strCon)
                Using (cmdSQL)
                    cmdSQL.Connection = conn
                    conn.Open()
                    rstData.Load(cmdSQL.ExecuteReader)
                End Using
            End Using
    
            Return rstData
    
        End Function
    
    Edit:
    I should point out that I used this test table structure:
    

    enter image description here

    As pointed out, the "image" type column is somewhat depreciated. However, even in the latest edition of SQL server, I do see "image" as a column type. If you are still using "image" type, then of course change this line:

    cmdSQL.Parameters.Add("@BImage", SqlDbType.VarBinary).Value = iBytes 
    

    to

     cmdSQL.Parameters.Add("@BImage", SqlDbType.Image).Value = iBytes