I know that there are already a couple of questions which seems like my problem but I tried to copy a lot of it and tried but can’t get the resold I want.
Actually is my target to save an image from a Picture Box as Byte() into mySQL Database.
At first I tried the simple way like
Dim acCust As Image = pgbox.image
Dim picBytes() As Byte
Using ms As New MemoryStream
cust.Save(ms, cust.RawFormat)
picBytes = ms.ToArray()
End Using
but with this I run into a general GUI error so I copied the Picture at first like this
Dim rec As New Rectangle(0, 0, acCust.Width, acCust.Height)
Dim mus As New ImageFormatConverter
Dim muster As New Bitmap(rec.Width, rec.Height)
Dim cust As Image
Using grp = Graphics.FromImage(muster)
grp.DrawImage(acCust, New Rectangle(0, 0, rec.Width, rec.Height), rec, GraphicsUnit.Pixel)
cust = muster
End Using
If I use after that again the code
Dim picBytes() As Byte
Using ms As New MemoryStream
cust.Save(ms, cust.RawFormat)
picBytes = ms.ToArray()
End Using
sqlconection.Open()
Dim query As String = "INSERT INTO tblimg(img) VALUES ('#image');"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("image", picBytes)
com.ExecuteNonQuery()
sqlconection.Close()
everything looks sofa ok but if I read it like this
Dim imgData As Byte()
Dim sql As String = "SELECT img FROM tblimg"
sqlconection.Open()
Dim cmd As New MySqlCommand(sql, sqlconection)
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
imgData = TryCast(rdr.Item("img"), Byte())
' in case this record has no image
If imgData IsNot Nothing Then
' ToDo: dispose of any previous Image
' create memstream from bytes
Using ms As New MemoryStream(imgData)
' create image from stream, assign to PicBox
pbbox.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
I got an alarm message
Eine nicht behandelte Ausnahme des Typs "System.ArgumentException" ist in System.Drawing.dll aufgetreten.
Zusätzliche Informationen: Ungültiger Parameter.
(Sorry it's in German)
Has anybody an idea what and were it’s going wrong?
If I use the the picByts () in a new memory stream and convert it back to an image then I got the correct result. It seems like there is a problem with the up or download query
in my Server I use the variable type LongBlob
You save a Byte array to a database in exactly the same way as you save any other data. You write your SQL, you add a parameter to a command and you set its value. This:
Dim query As String = "INSERT INTO tblimg(img) VALUES ('#image');"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("image", picBytes)
is wrong. You only wrap literal strings in single quotes in SQL code. That should be like this:
Dim query As String = "INSERT INTO tblimg(img) VALUES (#image);"
Dim com As New MySqlCommand(query, sqlconection)
com.Parameters.AddWithValue("#image", picBytes)
No single quotes around the parameter in the SQL and use the actual parameter name when adding it to the command. I'd also recommend using Add rather than AddWithValue but that's a discussion for another time.
Related
I tried retrieving data from MySQL to datagridview. The table contains an image column. When I remove the image column, the code works fine but it doesn't seem to work with the image column included.
Here's my code.
Mda= new mysldataadapter ("select * from user_info", con)
Dt = new datatable
Mda.fill(dt)
With datagridview1
. Datasource =dt
End with
I get this error msg
Datagridview default error dialog
System.argumentexception: parameter is not valid at
system.drawing.image.fromstream(....
Try using MemoryStream to store the image then show it... something like this :
Dim command As New MySqlCommand("SELECT `id`, `pic` FROM `mytb` WHERE `id` = #ID", connection)
command.Parameters.Add("#ID", MySqlDbType.UInt64).Value = TextBoxID.Text
Dim Adapter As New MySqlDataAdapter(command)
Dim DBTable As New DataTable()
Try
Adapter.Fill(DBTable)
Dim imgByte() As Byte
If DBTable.Rows.Count = 1 Then
imgByte = DBTable(0)(1)
Dim MS As New MemoryStream(imgByte)
PictureBox1.Image = Image.FromStream(MS)
End If
Catch ex As Exception
MessageBox.Show("ERROR")
PictureBox1.Image = Nothing
End Try
NOTE : The data type for the column must be BLOB.
Feel free to ask about anything you don't understand.
Hope that was helpful.
I've been attempting to adapt part of this procedure that I found online (can't remember where now!). I've been trying to use this to upload images to a MYSQL database using BLOB data type.
Public Sub SQLUpload()
Dim connection As New MySqlConnection(ConnectionImage)
Dim command As New MySqlCommand("INSERT INTO Images (File, FileName, FileSize) VALUES (#Picture, 'Name1', 'Size1')", connection)
'Create an Image object.'
Using picture As Image = Image.FromFile("C:\DIR\Pictures\Person.jpg")
'Create an empty stream in memory.'
Using stream As New IO.MemoryStream
'Fill the stream with the binary data from the Image.'
picture.Save(Stream, Imaging.ImageFormat.Jpeg)
'Get an array of Bytes from the stream and assign to the parameter.'
command.Parameters.AddWithValue("#Picture", SqlDbType.VarBinary).Value = stream.GetBuffer()
End Using
End Using
connection.Open()
Try
command.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub
Above is the current sub routine. Whenever this is executed, the routine operates fine until it gets to:
Command.ExecuteNonQuery()
It throws the error:
Unable to cast object of type System.Byte[] to type System.IConvertible
I'm pretty sure this happens because of the fact that the bytes from the image are returned as an array however the memory that they are saved to does not support an array? This was just gathered from reading I've done elsewhere online.
However, as this is not all my code I am frankly not sure what the problem is. Can anyone see what is wrong with it?
Many Thanks
Where you have
SqlDbType.VarBinary ' <-- this is Sql Server DB type
use
MySqlDbType.Blob
Like this
Dim file() As Byte = ' set your file
Dim p As MySqlParameter = new MySqlParameter("#Picture", MySqlDbType.Blob, file.Length)
p.Value = file
command.Parameters.Add(p)
As it mentioned by others, you don't need to "Save" your file - just read it into byte array. My code would look something like below:
Public Sub SQLUpload()
Try
Using conn As New MySqlConnection(connString)
' Parametarize entire sql string
Dim sql As String =
"INSERT INTO Images (File, FileName, FileSize) VALUES (#Picture, #name, #size)"
Using cmd As New MySqlCommand(sql, conn)
Dim fileName As String = "C:\DIR\Pictures\Person.jpg"
Dim file() As Byte = File.ReadAllBytes(fileName)
cmd.Parameters.AddWithValue("#Picture", MySqlDbType.Blob).Value = file
cmd.Parameters.AddWithValue("#file", MySqlDbType.VarChar).Value = fileName
cmd.Parameters.AddWithValue("#size", MySqlDbType.Int32).Value = file.Length
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Success")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
I am using service-based database (.mdf file) to add name and the photo to my database in VS 2010. After debugging and adding the data it adds up into the .mdf but while trying to retrieve it, it doesn't show. It shows only after next debugging. I am really stuck in this for 2 days please help me.
Thank you in advance.
Connection string I am currently using :
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=" & path & "Database1.mdf;Integrated Security=True;User Instance=True")
This is the code I am using to save the image and name :
Dim cmd As New SqlCommand("INSERT INTO Information VALUES(#name,#photo)", con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)
And this is the code I am using to display data in the datagridview
Me.InformationTableAdapter.Fill(Me.Database1DataSet.Information
I am trying to update a blob field based on id, with the following code but it always insert Null.
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
openconnection()
Dim cmd As New Odbc.OdbcCommand("UPDATE blob_table SET image=#PictureBox1 WHERE id='6'", myconnection)
Dim fs As New System.IO.FileStream("E:\Untitled.png", IO.FileMode.Open, IO.FileAccess.Read)
Dim b(fs.Length() - 1) As Byte
fs.Read(b, 0, b.Length)
fs.Close()
Dim P As Odbc.OdbcParameter = New Odbc.OdbcParameter("#PictureBox1", Odbc.OdbcType.Image, b.Length, ParameterDirection.Input, True, 0, 0, Nothing, DataRowVersion.Current, b)
cmd.Parameters.Add(P)
openconnection()
cmd.ExecuteNonQuery()
closeconnection()
End Sub
I check the connection, it is properly working,
The image path is a valid path. anyone can help me to find the mistake in the query?
I think you need to set the value of #PictureBox1 to a byte array - e.g. byte[] as I understand that's what the image blob type maps to instead of byte.
Try using a BinaryReader to populate your b byte array:
something like:
Dim b As Byte()
Dim br As New BinaryReader(fs)
b = br.ReadBytes(CInt(fs.Length))
br.Close()
fs.Close()
you have to do something like this to insert image to DB
Using pgFileStream As FileStream = New FileStream(productImageFilePath, FileMode.Open, FileAccess.Read)
Using pgReader As BinaryReader = New BinaryReader(New BufferedStream(pgFileStream))
Dim pgByteA As Byte() = pgReader.ReadBytes(CInt(pgFileStream.Length))
command.CommandText = " update gtab82 set memphoto=#Image where memuuid ='" & txtmemuid.Text & "' "
command.Parameters.AddWithValue("#Image", pgByteA)
command.ExecuteNonQuery()
End Using
End Using
am using PostgreSQL databse and my image field is bytea
I have stored Image as blob in mysql,And now I want ti display this image in picturebox in Vb,
I used Following code..
Dim con As New MySqlConnection
Dim str As String = "host=localhost;userid=root;password=;database=new;"
Dim qry As String = "select pic from img where id='1'"
Dim cmd As MySqlCommand
Dim reader As MySqlDataReader
Dim dt() As Byte
con.ConnectionString = str
Try
con.Open()
MsgBox(con.State)
cmd = New MySqlCommand(qry, con)
reader = cmd.ExecuteReader()
reader.Read()
dt = reader.Item("pic")
Dim mstream As New System.IO.MemoryStream
PictureBox1.Image = Image.FromStream(mstream)
reader.Close()
Catch ex As Exception
MsgBox(ErrorToString)
End Try
It shows connection state=1
but gives error Saying"Parameter is not valid,Whats wrong?"
You're creating a MemoryStream but not writing any data to it. The image data isn't going to magically come out of the stream; you have to put it there first. Have you done any reading on the MemoryStream class? If you have then you know that it has a constructor that allows you to pass in a Byte array. You have a Byte array containing the image data so that's a match made in heaven.
Also, make sure that you dispose the MemoryStream after using it.