| | |
Saving Drawing on PictureBox to SQL Database
Please support our VB.NET advertiser: Intel Parallel Studio Home
Thread Solved |
If you use adatapost's code:
use the Image property of the picture box
No, it's the image from the picture box converted to an array of bytes. You can't use the following SQL syntax with Image data type
Instead check, how adatapost used the parameters in the query (lines 8 - 32 from his post) If you looked my code, you'd seen that I used a parameter in the query too. And AFAIK that's the only way to do it.
•
•
•
•
I have my default picture so do I edit my code this way? but there is this prompt "Too many arguments to 'Public Function Save() As System.Drawing.Drawing2D.GraphicsState". so how do i solve this issue?
VB.NET Syntax (Toggle Plain Text)
'Write an image data into memory stream pbBody.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
•
•
•
•
How do I get the p2? isit the picturebox's name?
VB.NET Syntax (Toggle Plain Text)
Dim cmd As New SqlClient.SqlCommand("insert into image (myid,myimage) values ('" & Trim(lblId.text) & "','" & Trim(?) & "')", cn)
VB.NET Syntax (Toggle Plain Text)
'Memory stream Dim ms As New System.IO.MemoryStream 'Write an image data into memory stream pbBody.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png) 'To save an image into disk file 'pbBody.Image.Save("p1.png", System.Drawing.Imaging.ImageFormat.Png) 'Byte array Dim b() As Byte = ms.ToArray 'Parameterized Query Dim cmd As New SqlClient.SqlCommand("insert into mytable (myid,myimage) values (@p1,@p2)", cn) 'Create/add parameters '@p1 - name of parameter, datatype,size,"columnname" cmd.Parameters.Add("@p1", SqlDbType.Int, 4, "myid") cmd.Parameters.Add("@p2", SqlDbType.Image, b.Length, "myimage") 'Assign value to the parameters cmd.Parameters("@p1").Value = CInt(lblId.text) ' ASSUMING YOU'RE USING INT TYPE AS ID cmd.Parameters("@p2").Value = b ' THIS IS BYTE ARRAY CONTAINING THE IMAGE. SEE FEW LINES ABOVE
Teme64 @ Windows Developer Blog
•
•
Join Date: Apr 2009
Posts: 48
Reputation:
Solved Threads: 0
I have this prompt when I try to do my saving after drawing circle. [COLOR] Format of the initialization string does not conform to specification starting at index 0. [/COLOR]
Above is the line that is being highlighted for error.
Did i did the code correctly this time? how do i declare varchar's object expression?
Sorry if i'm stil as blur.
and my code for drawing multi circle..
Y does my circle's line alway gone missing when i scroll up n down my image?
VB.NET Syntax (Toggle Plain Text)
Dim cn As New System.Data.SqlClient.SqlConnection("CnStr")
Above is the line that is being highlighted for error.
Did i did the code correctly this time? how do i declare varchar's object expression?
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
'Memory stream
Dim ms As New System.IO.MemoryStream
'Write an image data into memory stream
pbBody.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
'Byte array
Dim b() As Byte = ms.ToArray
Dim cn As New System.Data.SqlClient.SqlConnection("CnStr")
'Parameterized Query
Dim cmd As New SqlClient.SqlCommand("insert into image (patientIC,picture) values (@p1,@p2)", cn)
'Create/add parameters
'@p1 - name of parameter, datatype,size,"columnname"
cmd.Parameters.Add("@p1", SqlDbType.VarChar, 50, "patientIC")
cmd.Parameters.Add("@p2", SqlDbType.Image, b.Length, "picture")
'Assign value to the parameters
cmd.Parameters("@p1").Value = __?__ (lblId.Text)
cmd.Parameters("@p2").Value = b
'Execute command
cn.Open()
cmd.ExecuteNonQuery()
End SubSorry if i'm stil as blur.
and my code for drawing multi circle..
VB.NET Syntax (Toggle Plain Text)
Private Sub pbBody_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pbBody.MouseDown 'Initialise Starting Points Of Shape, Once Mouse Button Is Pressed Down sStartX = e.X sStartY = e.Y End Sub Private Sub pbBody_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pbBody.MouseUp 'Initialise Ending Points Of Shape, Once Mouse Button Is Released sEndX = e.X sEndY = e.Y 'Draw The Circle With The Current Starting, And Ending Values. 'We must subtract the Starting values from the Ending values, 'to make sure the shape's Starting and ending values are 'precisely those where you started drawing, and where you 'ended drawing. pbBody.CreateGraphics.DrawEllipse(pPen, sStartX, sStartY, _ sEndX - sStartX, sEndY - sStartY) End Sub
Y does my circle's line alway gone missing when i scroll up n down my image?
•
•
•
•
Dim cn As New System.Data.SqlClient.SqlConnection("CnStr")
VB.NET Syntax (Toggle Plain Text)
Dim CnStr As String CnStr = "Data Source=MyMachineName\SQLEXPRESS; INITIAL CATALOG=MyDatabase; User ID=XXX; Password=XXX;" ' or CnStr = "Data Source=MyMachineName; INITIAL CATALOG=MyDatabase; User ID=XXX; Password=XXX;" Dim cn As New System.Data.SqlClient.SqlConnection(CnStr)
•
•
•
•
cmd.Parameters("@p1").Value = __?__ (lblId.Text)
VB.NET Syntax (Toggle Plain Text)
cmd.Parameters("@p1").Value = lblId.Text
•
•
•
•
Y does my circle's line alway gone missing when i scroll up n down my image?
I found two solution with googling. I didn't either test or try them so you'll have to check them yourself. First solution may be easier to modify for your needs. The latter one is for Pocket PC but should be portable to WinForms application:
I'm having a problem with drawing on picturebox in vb.net programing
and PictureBox Drawing VB.NET, here's the correct link to sample code: Scribbler Technology Sample
Teme64 @ Windows Developer Blog
•
•
Join Date: Apr 2009
Posts: 48
Reputation:
Solved Threads: 0
I still having problem for the re-draw part. i have added the codes below to my application:
The above codes only save what is being drew the latest. which mean only the new circle that is being draw wont disappear when i scroll up & down whereby the remainin circle will disappear.
Teme64 > I had try the 2 website that u gave me but i don't really get the way on how they do it.
VB.NET Syntax (Toggle Plain Text)
Private Sub pbBody_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pbBody.Paint 'Draw the Final rectangle, as a repaint was issued e.Graphics.DrawEllipse(pPen, sStartX, sStartY, _ sEndX - sStartX, sEndY - sStartY) End Sub Private Sub pbBody_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pbBody.Paint 'Draw the Final rectangle, as a repaint was issued e.Graphics.DrawEllipse(pPen, sStartX, sStartY, _ sEndX - sStartX, sEndY - sStartY) End Sub
The above codes only save what is being drew the latest. which mean only the new circle that is being draw wont disappear when i scroll up & down whereby the remainin circle will disappear.
Teme64 > I had try the 2 website that u gave me but i don't really get the way on how they do it.
Here's the repainting code. All the user drawings are saved on the arrays. On the picture box's paint event all the saved user drawings are repainted from the arrays
With this code you could also implement very easily "undo" option simply by decreasing array pointer (i.e. m_DrawIndex variable) and redimming arrays with the new array pointer value.
HTH
P.s. A short and quick answer: The first one is the code which converts image (i.e. Picturebox.Image property) to an array of bytes. This array of bytes can be saved to SQL Server's field of type Image. The latter code does that. There's also subroutines to retrieve the image back from the SQL Server to picture box control. Except that the latter link doesn't provide code for that, I just noticed
I'll try to write and post that code ASAP (I'm on holiday). Saving the Image type requires parametrized insert statement, maybe that's a bit confusing? And finally, adatapost's code does the same thing i.e. shows how to use parametrized queries.
VB.NET Syntax (Toggle Plain Text)
' "Drawing" arrays Private sStartX() As Integer Private sStartY() As Integer Private sEndX() As Integer Private sEndY() As Integer ' Remove New and (Color.White), they're just for debugging Private pPen As New System.Drawing.Pen(Color.White) ' DECLARE THIS AS AN ARRAY IF THE PEN CAN BE CHANGED ' Counter for the arrays, -1 = nothing drawed yet Private m_DrawIndex As Integer = -1 Private Sub PictureBox1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown 'Initialise Starting Points Of Shape, Once Mouse Button Is Pressed Down ' Start a new drawing: increase the counter and redim the arrays m_DrawIndex += 1 ReDim Preserve sStartX(m_DrawIndex) ReDim Preserve sStartY(m_DrawIndex) ReDim Preserve sEndX(m_DrawIndex) ReDim Preserve sEndY(m_DrawIndex) 'ReDim Preserve pPen(m_DrawIndex) ' Only if pPen is an array too ' sStartX(m_DrawIndex) = e.X sStartY(m_DrawIndex) = e.Y End Sub Private Sub PictureBox1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp 'Initialise Ending Points Of Shape, Once Mouse Button Is Released sEndX(m_DrawIndex) = e.X sEndY(m_DrawIndex) = e.Y 'Draw The Circle With The Current Starting, And Ending Values. 'We must subtract the Starting values from the Ending values, 'to make sure the shape's Starting and ending values are 'precisely those where you started drawing, and where you 'ended drawing. PictureBox1.CreateGraphics.DrawEllipse(pPen, sStartX(m_DrawIndex), sStartY(m_DrawIndex), _ sEndX(m_DrawIndex) - sStartX(m_DrawIndex), sEndY(m_DrawIndex) - sStartY(m_DrawIndex)) End Sub Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint 'Draw the Final rectangle, as a repaint was issued ' Redraw user drawings from the array Dim i As Integer For i = 0 To m_DrawIndex e.Graphics.DrawEllipse(pPen, sStartX(i), sStartY(i), _ sEndX(i) - sStartX(i), sEndY(i) - sStartY(i)) Next i End Sub
HTH
P.s.
•
•
•
•
I had try the 2 website that u gave me but i don't really get the way on how they do it.
I'll try to write and post that code ASAP (I'm on holiday). Saving the Image type requires parametrized insert statement, maybe that's a bit confusing? And finally, adatapost's code does the same thing i.e. shows how to use parametrized queries. Teme64 @ Windows Developer Blog
Here's a complete (example) code for saving a picture box control's image to SQL Server and loading it back
Create a new project (or just a form). Drop three button controls, one text box control and one picture box control to the form. Button1 saves the image, Button2 loads the image and Button3 clears the image (just for testing). I tried to comment the code so it should be understandable. The code is missing error handling and some "sanity checks" for the input to keep it short. And of course, you have to create a table for the data and replace connection string, table name and field names in the code.
HTH
VB.NET Syntax (Toggle Plain Text)
Option Strict On Option Explicit On Imports System.Drawing.Imaging ' Image related methods etc. Imports System.IO ' MemoryStream Imports System.Data.SqlClient ' SQl Server related classes Public Class Form1 ' Class global variable Private m_CnStr As String ' Connection string to DB ' Table structure: ' ImageTable: ' ' ImageID varchar(50) ' BlobField image ''' <summary> ''' Convert a byte array to an Image ''' </summary> ''' <param name="NewImage">Image to be returned</param> ''' <param name="ByteArr">Contains bytes to be converted</param> ''' <remarks></remarks> Public Sub Byte2Image(ByRef NewImage As Image, ByVal ByteArr() As Byte) ' Dim ImageStream As MemoryStream Try If ByteArr.GetUpperBound(0) > 0 Then ImageStream = New MemoryStream(ByteArr) NewImage = Image.FromStream(ImageStream) Else NewImage = Nothing End If Catch ex As Exception NewImage = Nothing End Try End Sub ''' <summary> ''' Convert an image to array of bytes ''' </summary> ''' <param name="NewImage">Image to be converted</param> ''' <param name="ByteArr">Returns bytes</param> ''' <remarks></remarks> Public Sub Image2Byte(ByRef NewImage As Image, ByRef ByteArr() As Byte) ' Dim ImageStream As MemoryStream Try ReDim ByteArr(0) If NewImage IsNot Nothing Then ImageStream = New MemoryStream NewImage.Save(ImageStream, ImageFormat.Jpeg) ReDim ByteArr(CInt(ImageStream.Length - 1)) ImageStream.Position = 0 ImageStream.Read(ByteArr, 0, CInt(ImageStream.Length)) End If Catch ex As Exception End Try End Sub ''' <summary> ''' Save a byte array to database ''' </summary> ''' <param name="ByteArr">Contains bytes to be saved</param> ''' <param name="ImageID">ID for the image</param> ''' <remarks></remarks> Public Sub SaveByteArray(ByVal ByteArr() As Byte, ByVal ImageID As String) ' Dim strSQL As String Dim oConn As SqlConnection Dim oCmd As SqlCommand Dim oVarCharParam As SqlParameter Dim oBLOBParam As SqlParameter Try ' Create and open connection object oConn = New SqlConnection(m_CnStr) oConn.Open() ' Insert statement ' Notice that @BLOBValue is a placeholder for the actual data strSQL = "INSERT INTO ImageTable (ImageID, BlobField) VALUES (@IDValue, @BLOBValue)" ' Create a command object oCmd = oConn.CreateCommand() ' Set SQL statement oCmd.CommandText = strSQL ' Create a command parameter oVarCharParam = New SqlParameter("@IDValue", SqlDbType.VarChar, _ 50, ParameterDirection.Input.ToString) ' Set the actual data oVarCharParam.Value = ImageID ' Add this parameter to the command oCmd.Parameters.Add(oVarCharParam) ' Create a command parameter oBLOBParam = New SqlParameter("@BLOBValue", SqlDbType.Binary, _ ByteArr.Length, ParameterDirection.Input.ToString) ' Finally, set the actual data oBLOBParam.Value = ByteArr ' Add this parameter to the command oCmd.Parameters.Add(oBLOBParam) ' Execute SQL statement oCmd.ExecuteNonQuery() ' Close the connection oConn.Close() Catch ex As Exception End Try End Sub ''' <summary> ''' Load a byte array from database ''' </summary> ''' <param name="ByteArr">Contains bytes from the database</param> ''' <param name="ImageID">ID for the image</param> ''' <remarks></remarks> Public Sub LoadByteArray(ByRef ByteArr() As Byte, ByVal ImageID As String) ' Dim strSQL As String Dim oConn As SqlConnection Dim oCmd As SqlCommand Dim ValueFromDB As Object ' ExecuteScalar method returns an object Try ' Create and open connection object oConn = New SqlConnection(m_CnStr) oConn.Open() ' Select statement strSQL = "SELECT BlobField FROM ImageTable WHERE ImageID='" & ImageID & "'" ' Create a command object oCmd = oConn.CreateCommand() ' Set SQL statement oCmd.CommandText = strSQL ' Execute SQL statement ValueFromDB = oCmd.ExecuteScalar() ' Close the connection oConn.Close() ' Convert returned object to an array of bytes If ValueFromDB IsNot DBNull.Value Then ByteArr = CType(ValueFromDB, Byte()) End If Catch ex As Exception End Try End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' DEBUG: Load an (initial) image to picture box control PictureBox1.Image = Image.FromFile("D:\image.jpg") ' Initialize DB connection, REPLACE VALUES! ' m_CnStr = "Data Source=database name; INITIAL CATALOG=table name; User ID=user name; Password=user password;" m_CnStr = "Data Source=xxx\SQLEXPRESS; INITIAL CATALOG=xxx; User ID=xxx; Password=xxx;" ' DEBUG: Test image ID TextBox1.Text = "patient_image_001" End Sub Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click ' Saves the image from the picture box control to SQL Server Dim ImageByteArr(0) As Byte ' An array to hold image (bytes) Dim PatientID As String ' ID for the image ' Get ID from a text box control and remove spaces PatientID = TextBox1.Text.Trim ' Convert image to an array of bytes Image2Byte(PictureBox1.Image, ImageByteArr) ' Save an array of bytes to SQL Server's field of type Image SaveByteArray(ImageByteArr, PatientID) End Sub Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click ' Loads the image to the picture box control from SQL Server Dim ImageByteArr(0) As Byte ' An array to hold image (bytes) Dim PatientID As String ' ID for the image ' Get ID from a text box control and remove spaces PatientID = TextBox1.Text.Trim ' Load an array of bytes from SQL Server's field of type Image LoadByteArray(ImageByteArr, PatientID) ' Convert an array of bytes to image Byte2Image(PictureBox1.Image, ImageByteArr) End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click ' DEBUG: Clear the image PictureBox1.Image = Nothing End Sub End Class
HTH
Teme64 @ Windows Developer Blog
•
•
Join Date: Apr 2009
Posts: 48
Reputation:
Solved Threads: 0
thanks alot for the effort for the example coding. before your codes above, i was using:
The above codes manage to save the image and patient's IC to MSSQL (binary data in MSSQL) and the multi selection also works (it wont disappeared when scroll up & down). so do I stil put in the Byte2Image, Image2Byte, SaveByteArray, LoadByteArray or do I just leave it as it was now?
And I don't know what is contain in the binary data when i retrieve as I havent tried.
Btw my retrieval form is different form with this current form , do I stil do the same for the retrieval side in order to see wat is being save in the binary data? as for your codes is retrieval and sendin is in the same form right?
Thanks =)
VB.NET Syntax (Toggle Plain Text)
Imports System.Data Imports System.Data.SqlClient Imports System.IO Imports System.Drawing.Imaging Public Class Page_2 'Declare Starting Points For Drawn Objects Private sStartX() As Integer Private sStartY() As Integer 'Declare Ending points For Drawn Objects Private sEndX() As Integer Private sEndY() As Integer 'Create And Initialise Pens To Draw The Particular Outline Shapes With. Color : Black, Width : 1 Dim pPen As New Pen(Color.Black, 1) ' Counter for the arrays, -1 = nothing drawed yet Private m_DrawIndex As Integer = -1 Private Sub pbBody_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pbBody.MouseDown 'Initialise Starting Points Of Shape, Once Mouse Button Is Pressed Down ' Start a new drawing: increase the counter and redim the arrays m_DrawIndex += 1 ReDim Preserve sStartX(m_DrawIndex) ReDim Preserve sStartY(m_DrawIndex) ReDim Preserve sEndX(m_DrawIndex) ReDim Preserve sEndY(m_DrawIndex) sStartX(m_DrawIndex) = e.X sStartY(m_DrawIndex) = e.Y End Sub Private Sub pbBody_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pbBody.MouseUp 'Initialise Ending Points Of Shape, Once Mouse Button Is Released sEndX(m_DrawIndex) = e.X sEndY(m_DrawIndex) = e.Y 'Draw The Circle With The Current Starting, And Ending Values. 'We must subtract the Starting values from the Ending values, 'to make sure the shape's Starting and ending values are 'precisely those where you started drawing, and where you 'ended drawing. pbBody.CreateGraphics.DrawEllipse(pPen, sStartX(m_DrawIndex), sStartY(m_DrawIndex), _ sEndX(m_DrawIndex) - sStartX(m_DrawIndex), sEndY(m_DrawIndex) - sStartY(m_DrawIndex)) End Sub Private Sub pbBody_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pbBody.Paint 'Draw the Final rectangle, as a repaint was issued ' Redraw user drawings from the array Dim i As Integer For i = 0 To m_DrawIndex e.Graphics.DrawEllipse(pPen, sStartX(i), sStartY(i), _ sEndX(i) - sStartX(i), sEndY(i) - sStartY(i)) Next i End Sub Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click Dim connAdd4 As New SqlConnection _ ("Data Source=152.226.152.99\SQLEXPRESS,1433;" + "Initial Catalog=TAR;" + "User ID=Remote;" + "Password=123;") Dim mySQL As String 'Memory stream Dim ms As New System.IO.MemoryStream 'Write an image data into memory stream pbBody.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp) 'Byte array Dim b() As Byte = ms.ToArray connAdd4.Open() 'Parameterized Query mySQL = "insert into image (patientIC,picture) values (@p1,@p2)" Dim cmdAdd4 As New SqlCommand(mySQL, connAdd4) 'Create/add parameters '@p1 - name of parameter, datatype,size,"columnname" cmdAdd4.Parameters.Add("@p1", SqlDbType.VarChar, 50, "patientIC") cmdAdd4.Parameters.Add("@p2", SqlDbType.Image, b.Length, "picture") 'Assign value to the parameters cmdAdd4.Parameters("@p1").Value = txtId.Text cmdAdd4.Parameters("@p2").Value = b 'Execute command cmdAdd4.ExecuteNonQuery() connAdd4.Close() End Sub End Class
The above codes manage to save the image and patient's IC to MSSQL (binary data in MSSQL) and the multi selection also works (it wont disappeared when scroll up & down). so do I stil put in the Byte2Image, Image2Byte, SaveByteArray, LoadByteArray or do I just leave it as it was now?
And I don't know what is contain in the binary data when i retrieve as I havent tried.
Btw my retrieval form is different form with this current form , do I stil do the same for the retrieval side in order to see wat is being save in the binary data? as for your codes is retrieval and sendin is in the same form right?
Thanks =)
![]() |
Similar Threads
- txt to sql database (C#)
- Updating SQL database, Please help (C#)
- SQL Database Problem (C#)
- PLEASE HELP!....SQL Database problem.... (C#)
- Update SQL database automatically using VB6 (Visual Basic 4 / 5 / 6)
- SQL Database loop (C#)
- Insert into sql database (ASP.NET)
- Process very slow - SQL Database (MS SQL)
- Help with Roles Stored in SQL database (ASP.NET)
- Snyc'n Local SQL database online (MS SQL)
Other Threads in the VB.NET Forum
- Previous Thread: Help: Using Parameter Stored Procedure in Crystal Report
- Next Thread: canot find a column
| Thread Tools | Search this Thread |
.net 30minutes 2005 2008 access account arithmetic array basic binary bing button buttons center check code combobox component connectionstring crystalreport data database databasesearch datagrid datagridview date design dissertation dissertations dissertationthesis dropdownlist excel fade file-dialog folder ftp generatetags google gridview hardcopy image images input insert intel internet listview mobile monitor ms net networking objects output passingparameters peertopeervideostreaming picturebox picturebox1 plugin port print problem problemwithinstallation project remove save searchbox searchvb.net select serial server shutdown soap survey table tcp temperature text textbox timer toolbox trim update updown user vb vb.net vb.netcode vb.netformclosing()eventpictureboxmessagebox vb2008 vbnet view visual visualbasic visualbasic.net visualstudio visualstudio2008 web winforms wpf






