Saving Drawing on PictureBox to SQL Database

Please support our VB.NET advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Aug 2008
Posts: 710
Reputation: Teme64 will become famous soon enough Teme64 will become famous soon enough 
Solved Threads: 114
Teme64's Avatar
Teme64 Teme64 is offline Offline
Master Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #31
Aug 4th, 2009
I made a mistake in previous post. The code should have been
  1. ' Loads the image to the picture box control from SQL Server
  2. Dim ImageByteArr(0) As Byte ' An array to hold image (bytes)
  3. Dim patientIC As String ' Patient's IC for Image
  4.  
  5. ' Get ID from a text box control and remove spaces
  6. patientIC = txtId.Text.Trim
  7. ' Load an array of bytes from SQL Server's field of type Image
  8. LoadByteArray(ImageByteArr, patientIC)
  9. If ImageByteArr.Length <= 1 Then
  10. MsgBox("Empty byte array! patientIC='" & patientIC & "' might not exist?")
  11. End If
  12. ' Convert an array of bytes to image
  13. Dim TempImage As Image = Nothing
  14. Byte2Image(TempImage, ImageByteArr)
  15. If TempImage IsNot Nothing Then
  16. pbBody.Image = TempImage
  17. Else
  18. MsgBox("Image is nothing!")
  19. End If
Code line 9 changes a bit. Do you get now "Empty byte array..." message?

Two possibilities left. The ID patientIC is still not found. Or the saving of the image fails in the first place.

If you view the DB data in SQL Server Management Studio, it shows <Binary data> in the Image type field, but it may not be valid data. You could try to execute following SQL statement in Management Studio
  1. SELECT [ImageID], [BlobField]
  2. FROM [ImageTable]
  3. WHERE [ImageID]='patient101'
(just replace correct field and table names and ID value). You should now see if there's actually data in Image field:
ImageID BlobField
patient101 0xFFD8FFE000104A46494600010101006...
Image data is dumped in hex format but you'll see that there's actually some data in the field.

Another (and possible a better) way is to execute query
  1. SELECT DATALENGTH([BlobField]) AS DataLen
  2. FROM [ImageTable]
  3. WHERE [ImageID]='patient101'
I got the result
DataLen
2319
for an image. This is a value you can compare to the length of data you're originally saving. You had (my variable names, sorry) Image2Byte(Form2.BitmapCanvas, ImageByteArr) in your code. Write after that line MsgBox(ImageByteArr.Length) and compare those two lengths, they should be the same.

I hope this didn't get too complicated There's some small bug left in the code, but it's hard to catch.
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 48
Reputation: DAWNIE is an unknown quantity at this point 
Solved Threads: 0
DAWNIE DAWNIE is offline Offline
Light Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #32
Aug 4th, 2009
If ImageByteArr.Length < 1 Then

to

If ImageByteArr.Length <= 1 Then
after editing the above code, i did receive the "Empty byte array..." message.

but if the id is not exist, then how could i retrieve the other data and not the image whereby they are in the same DB jus different table only?

Image2Byte(Form2.BitmapCanvas, ImageByteArr)
I didnt manage to find the above code in my codes... i only found
  1. Public Sub Image2Byte(ByVal NewImage As Image, ByRef ByteArr() As Byte)

and i had try the excute SQL statement in SQL Studio and the result I get is:

patientIC image
S7654321W 0x00
and for datalen

DataLen
1
doesnt that means my image is an invalid 1?

yaya, the bug is real hard to solve but hopefully is not a bug that due to my careless if not i will gonna go bang the wall =)
Last edited by DAWNIE; Aug 4th, 2009 at 6:20 am.
Reply With Quote Quick reply to this message  
Join Date: May 2009
Posts: 5
Reputation: a.j. is an unknown quantity at this point 
Solved Threads: 1
a.j. a.j. is offline Offline
Newbie Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #33
Aug 4th, 2009
Can someone please tell me what program to use...i want to draw up logos for a club in school. i dont even know how i am going to go about this. please help!!!!
-: a.j.
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 710
Reputation: Teme64 will become famous soon enough Teme64 will become famous soon enough 
Solved Threads: 114
Teme64's Avatar
Teme64 Teme64 is offline Offline
Master Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #34
Aug 5th, 2009
and i had try the excute SQL statement in SQL Studio and the result I get is:
patientIC image
S7654321W 0x00
and for datalen
DataLen
1
doesnt that means my image is an invalid 1?
Yes, the image isn't saved correctly. Did you use adatapost's code (Post #9 in Saving Drawing on PictureBox to SQL Database) for saving the image?

I slightly modified the "save image to DB" code
  1. 'Memory stream
  2. Dim ms As New System.IO.MemoryStream
  3. 'Write an image data into memory stream
  4. DrawingForm.BitmapCanvas.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
  5.  
  6. 'Byte array
  7. Dim b() As Byte = ms.ToArray
  8. Dim cn As New System.Data.SqlClient.SqlConnection(m_CnStr) ' <-- your connection string goes here
  9. 'Parameterized Query
  10. Dim cmd As New SqlClient.SqlCommand("insert into image (patientIC,picture) values (@p1,@p2)", cn) ' <-- your table/field names go here
  11. 'Create/add parameters
  12. Dim oVarCharParam As SqlParameter = New SqlParameter("p1", SqlDbType.VarChar, 50, ParameterDirection.Input.ToString)
  13. oVarCharParam.Value = "image01" ' lblId.Text, I use a hard coded ID here for debugging
  14. cmd.Parameters.Add(oVarCharParam)
  15. 'Create/add parameters
  16. Dim oBLOBParam As SqlParameter = New SqlParameter("@p2", SqlDbType.Binary, b.Length, ParameterDirection.Input.ToString)
  17. oBLOBParam.Value = b
  18. cmd.Parameters.Add(oBLOBParam)
  19.  
  20. 'Execute command
  21. cn.Open()
  22. cmd.ExecuteNonQuery()
  23.  
  24. cn.Close() ' <-- close the connection unless you need it
to ensure that ParameterDirection is correct.

You should also check all your code, what System.Drawing.Imaging.ImageFormat enumeration value you use with images. It shouldn't make any difference what image format you use, but you have to use the same format (like Jpeg) for both saving and retrieving the image from the DB. If you used the original posting with Png format and later tried to get image back with my code (Jpeg format), that didn't cause an empty image to be saved.

You could also put MsgBox(b.Length) to the code above ("between" lines 7 and 8) to check the original image size. You should get the same value with SQL statement (from my previous posting) containing DataLen function after you've saved a new image.
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 48
Reputation: DAWNIE is an unknown quantity at this point 
Solved Threads: 0
DAWNIE DAWNIE is offline Offline
Light Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #35
Aug 5th, 2009
i didnt put that codes cos i thought this codes already saving the image to DB

  1. Public Sub Image2Byte(ByVal NewImage As Image, ByRef ByteArr() As Byte)
  2. '
  3. Dim ImageStream As MemoryStream
  4.  
  5. Try
  6. ReDim ByteArr(0)
  7. If NewImage IsNot Nothing Then
  8. ImageStream = New MemoryStream
  9. NewImage.Save(ImageStream, ImageFormat.Jpeg)
  10. ReDim ByteArr(CInt(ImageStream.Length - 1))
  11. ImageStream.Position = 0
  12. ImageStream.Read(ByteArr, 0, CInt(ImageStream.Length))
  13. End If
  14. Catch ex As Exception
  15.  
  16. End Try
  17.  
  18. End Sub
  19.  
  20. Public Sub SaveByteArray(ByVal ByteArr() As Byte, ByVal patientIC As String)
  21. '
  22. Dim mySQL As String
  23. Dim cmdAdd4 As SqlCommand
  24. Dim oVarCharParam As SqlParameter
  25. Dim oBLOBParam As SqlParameter
  26.  
  27. Try
  28. ' Create and open connection object
  29. Dim connAdd4 As New SqlConnection _
  30. ("Data Source=DATASOURCE;" + "Initial Catalog=DBNAME;" + "User ID=UID;" + "Password=PW;")
  31. connAdd4.Open()
  32. ' Insert statement
  33. ' Notice that @BLOBValue is a placeholder for the actual data
  34. mySQL = "INSERT INTO image (patientIC, picture) VALUES (@IDValue, @BLOBValue)"
  35. ' Create a command object
  36. cmdAdd4 = connAdd4.CreateCommand()
  37. ' Set SQL statement
  38. cmdAdd4.CommandText = mySQL
  39. ' Create a command parameter
  40. oVarCharParam = New SqlParameter("@IDValue", SqlDbType.VarChar, _
  41. 50, ParameterDirection.Input.ToString)
  42. ' Set the actual data
  43. oVarCharParam.Value = patientIC
  44. ' Add this parameter to the command
  45. cmdAdd4.Parameters.Add(oVarCharParam)
  46. ' Create a command parameter
  47. oBLOBParam = New SqlParameter("@BLOBValue", SqlDbType.Binary, _
  48. ByteArr.Length, ParameterDirection.Input.ToString)
  49. ' Finally, set the actual data
  50. oBLOBParam.Value = ByteArr
  51. ' Add this parameter to the command
  52. cmdAdd4.Parameters.Add(oBLOBParam)
  53. ' Execute SQL statement
  54. cmdAdd4.ExecuteNonQuery()
  55. ' Close the connection
  56. connAdd4.Close()
  57. Catch ex As Exception
  58.  
  59. End Try
  60.  
  61. End Sub

m i wrong?
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 710
Reputation: Teme64 will become famous soon enough Teme64 will become famous soon enough 
Solved Threads: 114
Teme64's Avatar
Teme64 Teme64 is offline Offline
Master Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #36
Aug 7th, 2009
m i wrong?
No. Just more debugging needed.

Here's the same code with four messagebox "dumps" added
  1. Public Sub Image2Byte(ByVal NewImage As Image, ByRef ByteArr() As Byte)
  2. '
  3. Dim ImageStream As MemoryStream
  4.  
  5. Try
  6. ReDim ByteArr(0)
  7. If NewImage IsNot Nothing Then
  8. ImageStream = New MemoryStream
  9. NewImage.Save(ImageStream, ImageFormat.Jpeg)
  10. ReDim ByteArr(CInt(ImageStream.Length - 1))
  11. ImageStream.Position = 0
  12. ImageStream.Read(ByteArr, 0, CInt(ImageStream.Length))
  13. MsgBox(ByteArr.Length) ' DEBUG
  14. End If
  15. Catch ex As Exception
  16. MsgBox(ex.Message) ' DEBUG
  17. End Try
  18.  
  19. End Sub
  20.  
  21. Public Sub SaveByteArray(ByVal ByteArr() As Byte, ByVal patientIC As String)
  22. '
  23. Dim mySQL As String
  24. Dim cmdAdd4 As SqlCommand
  25. Dim oVarCharParam As SqlParameter
  26. Dim oBLOBParam As SqlParameter
  27.  
  28. Try
  29. MsgBox(ByteArr.Length) ' DEBUG
  30. ' Create and open connection object
  31. Dim connAdd4 As New SqlConnection _
  32. ("Data Source=DATASOURCE;" + "Initial Catalog=DBNAME;" + "User ID=UID;" + "Password=PW;")
  33. connAdd4.Open()
  34. ' Insert statement
  35. ' Notice that @BLOBValue is a placeholder for the actual data
  36. mySQL = "INSERT INTO image (patientIC, picture) VALUES (@IDValue, @BLOBValue)"
  37. ' Create a command object
  38. cmdAdd4 = connAdd4.CreateCommand()
  39. ' Set SQL statement
  40. cmdAdd4.CommandText = mySQL
  41. ' Create a command parameter
  42. oVarCharParam = New SqlParameter("@IDValue", SqlDbType.VarChar, _
  43. 50, ParameterDirection.Input.ToString)
  44. ' Set the actual data
  45. oVarCharParam.Value = patientIC
  46. ' Add this parameter to the command
  47. cmdAdd4.Parameters.Add(oVarCharParam)
  48. ' Create a command parameter
  49. oBLOBParam = New SqlParameter("@BLOBValue", SqlDbType.Binary, _
  50. ByteArr.Length, ParameterDirection.Input.ToString)
  51. ' Finally, set the actual data
  52. oBLOBParam.Value = ByteArr
  53. ' Add this parameter to the command
  54. cmdAdd4.Parameters.Add(oBLOBParam)
  55. ' Execute SQL statement
  56. cmdAdd4.ExecuteNonQuery()
  57. ' Close the connection
  58. connAdd4.Close()
  59. Catch ex As Exception
  60. MsgBox(ex.Message) ' DEBUG
  61. End Try
  62.  
  63. End Sub
When you save the image, you should get the image size twice. If you get an error message (from MsgBox(ex.Message)) then post the error message.

Image2Byte(Form2.BitmapCanvas, ImageByteArr)
I didnt manage to find the above code in my codes... i only found
Public Sub Image2Byte(ByVal NewImage As Image, ByRef ByteArr() As Byte)
You should have a call like
Image2Byte(DrawingForm.BitmapCanvas, ImageByteArr)
followed by
SaveByteArray(ImageByteArr, patientIC)
If you don't have (notice that the actual parameter names may differ a bit), check that you do call them after you return from your DrawingForm back to main form and you haven't disposed DrawingForm yet.

The subroutines themselves are ok and your drawing form's code should be ok. You either didn't save the image buffer (i.e. DrawingForm.BitmapCanvas) in the first place or something goes wrong when you try to save a byte array to image field

My original sample code had "empty" exception handlers
  1. Catch ex As Exception
  2.  
  3. End Try
but you should at least put a breakpoint or MsgBox
  1. Catch ex As Exception
  2. MsgBox(ex.Message) ' DEBUG
  3. End Try
to see if something does go wrong.
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 48
Reputation: DAWNIE is an unknown quantity at this point 
Solved Threads: 0
DAWNIE DAWNIE is offline Offline
Light Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #37
Aug 7th, 2009
after putting the four msgbox, i have a popup box. In the popup box, there is number "1" or "ok" button. does that means the datalen?

when i retrieve, it still prompt mi ""Empty byte array..." message and "image is nothing" kind of prompt. Other data appear except images.


You should have a call like
Image2Byte(DrawingForm.BitmapCanvas, ImageByteArr)
followed by
SaveByteArray(ImageByteArr, patientIC)
the above "ImageByteArr" is in another form so how can i input the codes to saving form whereby the ImageByteArr will not have a curly line under it?
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 710
Reputation: Teme64 will become famous soon enough Teme64 will become famous soon enough 
Solved Threads: 114
Teme64's Avatar
Teme64 Teme64 is offline Offline
Master Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #38
Aug 7th, 2009
the above "ImageByteArr" is in another form so how can i input the codes to saving form whereby the ImageByteArr will not have a curly line under it?
Add declaration
  1. Dim ImageByteArr(0) As Byte ' An array to hold image (bytes)
right before calling
  1. Image2Byte(DrawingForm.BitmapCanvas, ImageByteArr)
  2. ' and after that
  3. SaveByteArray(ImageByteArr, patientIC)
After declaring that byte array, could you change MsgBox(ByteArr.Length) ' DEBUG to MsgBox("Image2Byte " & ByteArr.Length) ' DEBUG in Image2Byte procedure and MsgBox(ByteArr.Length) ' DEBUG to MsgBox("SaveByteArray " & ByteArr.Length) ' DEBUG in SaveByteArray procedure, so that it would be clear at which point byte array remains or gets empty.

Also, change in Image2Byte procedure
  1. If NewImage IsNot Nothing Then
  2. ImageStream = New MemoryStream
  3. NewImage.Save(ImageStream, ImageFormat.Jpeg)
  4. ReDim ByteArr(CInt(ImageStream.Length - 1))
  5. ImageStream.Position = 0
  6. ImageStream.Read(ByteArr, 0, CInt(ImageStream.Length))
  7. MsgBox(ByteArr.Length) ' DEBUG
  8. Else ' <-- ADD THIS ELSE PART TO TRAP MISSING IMAGE PARAM
  9. MsgBox("Image is nothing") ' DEBUG
  10. End If
this will prompt if you call it with a non-existing image. If you do get "Image is nothing" prompt, your DrawingForm.BitmapCanvas is empty (i.e. Nothing) at the point when you call this procedure.

In the popup box, there is number "1" or "ok" button. does that means the datalen?
Yes. Actually this is length of the byte array but it should be same as the final data length in the DB.

when i retrieve, it still prompt mi ""Empty byte array..." message and "image is nothing" kind of prompt. Other data appear except images.
There's still some problem in saving the image. Once that is solved, you'll get the image too (I keep my fingers crossed).
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 48
Reputation: DAWNIE is an unknown quantity at this point 
Solved Threads: 0
DAWNIE DAWNIE is offline Offline
Light Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #39
Aug 10th, 2009
i've attached my printscreen for my error...

the codes that i hav edit according to ur instruction is so far like that:

  1. ''' <summary>
  2. ''' Convert an image to array of bytes
  3. ''' </summary>
  4. ''' <param name="NewImage">Image to be converted</param>
  5. ''' <param name="ByteArr">Returns bytes</param>
  6. ''' <remarks></remarks>
  7. '''
  8. Public Sub Image2Byte(ByVal NewImage As Image, ByRef ByteArr() As Byte)
  9.  
  10. Dim ImageByteArr(0) As Byte ' An array to hold image (bytes)
  11. Dim patientIC As String ' ID for the image
  12.  
  13. Image2Byte(Drawing.BitmapCanvas, ImageByteArr)
  14.  
  15. SaveByteArray(ImageByteArr, patientIC)
  16.  
  17. Dim ImageStream As MemoryStream
  18.  
  19. Try
  20. If NewImage IsNot Nothing Then
  21. ImageStream = New MemoryStream
  22. NewImage.Save(ImageStream, ImageFormat.Jpeg)
  23. ReDim ByteArr(CInt(ImageStream.Length - 1))
  24. ImageStream.Position = 0
  25. ImageStream.Read(ByteArr, 0, CInt(ImageStream.Length))
  26. MsgBox("Image2Byte " & ByteArr.Length) ' DEBUG
  27. Else
  28. MsgBox("Image is nothing") 'DEBUG
  29. End If
  30. Catch ex As Exception
  31. MsgBox(ex.Message) ' DEBUG
  32. End Try
  33.  
  34. End Sub
  35.  
  36. ''' <summary>
  37. ''' Save a byte array to database
  38. ''' </summary>
  39. ''' <param name="ByteArr">Contains bytes to be saved</param>
  40. ''' <param name="patientIC">ID for the image</param>
  41. ''' <remarks></remarks>
  42. Public Sub SaveByteArray(ByVal ByteArr() As Byte, ByVal patientIC As String)
  43. '
  44. Dim mySQL As String
  45. Dim cmdAdd4 As SqlCommand
  46. Dim oVarCharParam As SqlParameter
  47. Dim oBLOBParam As SqlParameter
  48.  
  49. Try
  50. MsgBox("SaveByteArray " & ByteArr.Length) ' DEBUG
  51. ' Create and open connection object
  52. Dim connAdd4 As New SqlConnection _
  53. ("Data Source=DATASOURCE;" + "Initial Catalog=DBNAME;" + "User ID=UID;" + "Password=PW;")
  54. connAdd4.Open()
  55. ' Insert statement
  56. ' Notice that @BLOBValue is a placeholder for the actual data
  57. mySQL = "INSERT INTO image (patientIC, picture) VALUES (@IDValue, @BLOBValue)"
  58. ' Create a command object
  59. cmdAdd4 = connAdd4.CreateCommand()
  60. ' Set SQL statement
  61. cmdAdd4.CommandText = mySQL
  62. ' Create a command parameter
  63. oVarCharParam = New SqlParameter("@IDValue", SqlDbType.VarChar, _
  64. 50, ParameterDirection.Input.ToString)
  65. ' Set the actual data
  66. oVarCharParam.Value = patientIC
  67. ' Add this parameter to the command
  68. cmdAdd4.Parameters.Add(oVarCharParam)
  69. ' Create a command parameter
  70. oBLOBParam = New SqlParameter("@BLOBValue", SqlDbType.Binary, _
  71. ByteArr.Length, ParameterDirection.Input.ToString)
  72. ' Finally, set the actual data
  73. oBLOBParam.Value = ByteArr
  74. ' Add this parameter to the command
  75. cmdAdd4.Parameters.Add(oBLOBParam)
  76. ' Execute SQL statement
  77. cmdAdd4.ExecuteNonQuery()
  78. ' Close the connection
  79. connAdd4.Close()
  80. Catch ex As Exception
  81. MsgBox(ex.Message) ' DEBUG
  82. End Try
  83.  
  84. End Sub
  85.  
  86. Private Sub btnOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOpen.Click
  87.  
  88. Dim ImageByteArr(0) As Byte ' An array to hold image (bytes)
  89. Dim patientIC As String ' ID for the image
  90.  
  91. Drawing.ShowDialog() ' Draw the image first
  92.  
  93. ' Get ID from a text box control and remove spaces
  94. patientIC = txtId.Text.Trim
  95. ' Convert image to an array of bytes
  96. Image2Byte(pbBody.Image, ImageByteArr)
  97. ' Save an array of bytes to SQL Server's field of type Image
  98. SaveByteArray(ImageByteArr, patientIC)
  99.  
  100. End Sub

but y cant i dim patientIC As String on the Image2Byte procedure? whereby i'm able to dim it as String in OPEN to drawingform prodecure?

the error i received for dimming patientIC as String is "Variable 'patientIC' is used before it has been assigned a value. A null reference exception could result at runtime"

should i dim it as integer instead?
Attached Thumbnails
PrintScreen.JPG  
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 48
Reputation: DAWNIE is an unknown quantity at this point 
Solved Threads: 0
DAWNIE DAWNIE is offline Offline
Light Poster

Re: Saving Drawing on PictureBox to SQL Database

 
0
  #40
Aug 14th, 2009
Teme64, I have solve the problem regarding my codes... it becos of 1 typo error...

  1.  
  2. Private Sub btnOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOpen.Click
  3.  
  4. ' Saves the image from the bitmap buffer to SQL Server
  5. Dim ImageByteArr(0) As Byte ' An array to hold image (bytes)
  6. Dim patientIC As String ' ID for the image
  7.  
  8. Drawing.ShowDialog() ' Draw the image first
  9.  
  10. ' Get ID from a text box control and remove spaces
  11. patientIC = lblId.Text.Trim
  12. ' Convert image to an array of bytes
  13. ' USE FORM2 BITMAP, NOT PICTURE BOX CONTROL
  14. [COLOR="Red"] Image2Byte(Drawing.BitmapCanvas, ImageByteArr)[/COLOR]
  15. ' Save an array of bytes to SQL Server's field of type Image
  16. SaveByteArray(ImageByteArr, patientIC)
  17.  
  18. End Sub

the sentence that is red in colour is what it shld be... but that time i went to type [ Image2Byte(pbBody.Image, ImageByteArr)]..

sry for my typo error that time =)
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC