Retrieving Image from Mysql using vb.net - mysql

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.

Related

how to save a byte() to my SQLDatabase using VB.net

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.

Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible' when updating an image to MySQL database

I'm having trouble updating images into my database in MySQL.
I'm using a combobox to select a user ID and populate that combobox with that ID and the image that's associated with that ID on a picturebox
I can add and remove images just fine, but the problem is when I try to update any image i get the error " Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible' ".
I've looked it up and it has something to do with passing an array of bytes to a single byte, which is not possible.
Here's my code to update the image:
Dim filesize As UInteger
Dim imgcliente As New MemoryStream
PictureBox1.Image.Save(imgcliente, PictureBox1.Image.RawFormat)
Dim arrImage As Byte() = imgcliente.GetBuffer
filesize = imgcliente.Length
imgcliente.Close()
And here's my code to retrive the associated image from the ID:
cmd = New MySqlCommand("SELECT Imagem_Cliente FROM adegages.clientes WHERE ID_Cliente='" & cmb_cliente.Text & "'", con)
Dim imagedata As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imagedata Is Nothing Then
Using ms As New System.IO.MemoryStream(imagedata, 0, imagedata.Length)
ms.Write(imagedata, 0, imagedata.Length)
PictureBox1.Image = New Bitmap(Image.FromStream(ms, True))
End Using
End If
It's probably just some line and it may be incredibly ease to solve, but I just can't seem to figure out where I'm wrong.
Thx in advance
Edit:
This is the code to edit records to the database
Dim atualizar_vendas As New MySqlCommand("UPDATE vendas SET ID_Venda=#ID,
Cliente_Venda=#CLIENTE, Data_Venda=#DATA, Qnt_Vinho_Venda=#QNT,
Tipo_Casta_Venda=#TIPO_CASTA, Nome_Casta_Venda=#NOME_CASTA,
Total_Venda=#TOTAL, Imagem_Cliente=#IMG WHERE ID_Venda = #ID", con)
atualizar_vendas.Parameters.Add("#ID", MySqlDbType.Int32).Value = txt_id_venda.Text
atualizar_vendas.Parameters.Add("#CLIENTE", MySqlDbType.VarChar).Value = cmb_cliente.Text
atualizar_vendas.Parameters.Add("#DATA", MySqlDbType.VarChar).Value = mtx_data_venda.Text
atualizar_vendas.Parameters.Add("#QNT", MySqlDbType.VarChar).Value = txt_qnt_vendida.Text
atualizar_vendas.Parameters.Add("#TIPO_CASTA", MySqlDbType.VarChar).Value = cmb_tipo_casta.Text
atualizar_vendas.Parameters.Add("#NOME_CASTA", MySqlDbType.VarChar).Value = cmb_nome_casta.Text
atualizar_vendas.Parameters.Add("#TOTAL", MySqlDbType.VarChar).Value = txt_total.Text
atualizar_vendas.Parameters.Add("#IMG", MySqlDbType.Int32).Value = arrImage
Try
con.Open()
If atualizar_vendas.ExecuteNonQuery() > 0 Then
MsgBox("Editado com sucesso!", MsgBoxStyle.Information, "AdegaGes")
Limpar()
End If
con.Close()
Retrieve_Clientes()
Retrieve_Tipo_Casta()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "AdegaGes")
con.Close()
Finally
con.Dispose()
cmd.Dispose()
End Try
Take a look at this:
atualizar_vendas.Parameters.Add("#IMG", MySqlDbType.Int32).Value = arrImage
That parameter is asking for a single integer, instead of a byte array. You probably want MySqlDbType.Blob there instead.

Display saved PDF file from database to PDFVIEWER

I have successfully saved a pdf file to my database (MySQL) as a longblob and used this code :
opf.Filter = "PDF FILES |*.pdf"
If opf.ShowDialog = Windows.Forms.DialogResult.OK Then
//Display the PDF you want to save in the PDFVIEWER
pdfview.src = opf.FileName
Dim Mystream As New FileStream(opf.FileName, FileMode.Open)
Dim filesize As Long = Mystream.Length
Dim buffer(filesize) As Byte
Mystream.Read(buffer, 0, filesize)
//Save the pdf file to the database
Dim query As String = "insert into sample(pdfnaho)values(#file)"
Dim cmd As New MySqlCommand(query, con)
con.Open()
cmd.Parameters.AddWithValue("#file", buffer)
cmd.ExecuteNonQuery()
MsgBox("SAVED!")
con.Close()
End If
Then I used this code for displaying but It doesn't work and I don't know what to do :
Dim query As String = "select * from sample where id = 1"
Dim cmd As New MySqlCommand(query, con)
con.Open()
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
If dr.HasRows Then
pdfview.src = dr.GetString("pdfnaho")
End If
End While
con.Close()
How should I display my saved pdf file from database? Thank You
I can not put this as a comment because I don't have enough reputation.
What PDF viewer are you using?. If it is the Adobe PDF Viewer I am almost sure (from previous research for another project) that you can not stream into it.
This is an example from my previous project, I modified it to fit yours, make sure to edit the query to fit your table and columns names.
You have to ran a query that return only the cell with the file in binary.
Dim query as String = "SELECT file_content FROM sample WHERE ID=1;"
Public Sub OpenPDF()
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
pdfview.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New MySqlCommand(query, con)
Dim Buffer As Byte()
con.open()
Buffer = cmd.ExecuteScalar
con.close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
pdfview.src = Application.StartupPath() & "\temp.file"
End Sub
With this example, the code will check if there is an existing "temp.file" and delete it, then load nothing on the pdfviewer to clear whatever is displaying.
The the database connection, get the data, store it on a file then display it with the pdfviewer.

Loop through Database table and get all values of each record in turn

I need to get all the values of each record in a table, this is so I can then add them to a text file log, a record per line, and then delete them from the database. I'm new to this and have searched how to add SQL query results to an array or a generic list, but I don't fully understand them.
All I have so far is:
Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Dim strSQl = "TRUNCATE TABLE CurrentJobs"
Dim commandInsert As New OleDbCommand
commandInsert.CommandText = strSQl
commandInsert.Connection = conn
commandInsert.Connection.Open()
commandInsert.ExecuteNonQuery()
Me.ReportViewer1.RefreshReport()
End Sub
This is for a Uni project, and above is how we have been to shown to do it, however nothing I have found while researching looks similar.
Feel free to use this procedure:
Private Sub DataTableToTextFile()
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Using conn As OleDbConnection = New OleDbConnection(connString)
Dim dt As New DataTable
conn.Open()
'Change the query. It's not a good practice to use '*' in your select queries. Please, use the column names instead.
Dim dataAdapter As New OleDbDataAdapter("SELECT * FROM CurrentJobs", conn)
dataAdapter.Fill(dt)
'Change the path to your desired path
Dim exportPath As String = "C:\Logs\"
Dim exportFileName As String = "log.txt"
'If directory does not exists, create it
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
'Write data into the text file
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
sb = New StringBuilder
For Each col As DataColumn In dt.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
'Finally clean database table
Dim strSQl = "Delete From CurrentJobs"
Dim commandDelete As New OleDbCommand(strSQl, conn)
'execute
commandDelete.ExecuteNonQuery()
'close connection
conn.Close()
End Using
End Sub

How to save image in database without ruin the picture?

I have a problem regarding on saving the image on database using BLOB data type, it save the image successfully but when i retrieve it using my picture box it ruins my image. ill show you the screenshot on my application. I am using vb.net.
this is my codes on saving image file in blob data type.
Dim filename As String = Me.OpenFileDialog1.FileName
Dim FileSize As UInt32
Dim conn As New MySqlConnection
conn = New MySqlConnection("server=localhost;user=root;password=;database=ticketing_system;")
conn.Open()
Dim mstream As New System.IO.MemoryStream()
Me.PbPicture.Image = Image.FromFile(Me.OpenFileDialog1.FileName)
Me.PbPicture.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
Dim sqlcmd As New MySql.Data.MySqlClient.MySqlCommand
Dim sql As String
mstream.Close()
' DBconn.Close()
sql = "INSERT INTO clientreports(img)VALUES(#File)"
Try
' DBconn.Open()
With sqlcmd
.CommandText = sql
.Connection = conn
.Parameters.AddWithValue("#File", arrImage)
.ExecuteNonQuery()
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Close()
End Try
here is my code on displaying my image on picturebox.
Dim strSQL As String
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
conn = New MySqlConnection("server=localhost;user=root;password=;database=ticketing_system;")
Dim SQLConnection As MySqlConnection = New MySqlConnection
'Dim connection As New SqlConnection("connection string here")
Dim command As New MySqlCommand("SELECT img FROM errdeschis where err_id='31'", conn)
conn.Open()
Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
conn.Close()
Dim picture As Image = Nothing
'Create a stream in memory containing the bytes that comprise the image.
Using stream As New IO.MemoryStream(pictureData)
'Read the stream and create an Image object from the data.
PictureBox1.Image = Image.FromStream(stream)
End Using
please guys help me.
OKAY.Use MEDIUMBLOB or LONGBLOB for the field.
Have you tried psren `s answer?
changed BLOB to LONGBLOB
It works for me!