How to save image in database without ruin the picture? - mysql

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!

Related

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.

Getting all the rows of a MySQL table and putting them in a listbox

I want to get all the rows of table of a MySQL database and store them in a listbox. I am using vb.net. Thanks in advance.
Dim connection As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim Column0 As String
connection.ConnectionString = "Data Source=localhost; Initial Catalog=catalogname; Integrated Security=True; Connection Timeout=3"
Dim query As String = "SELECT * FROM MyDB"
connection.Open()
cmd = New SqlCommand(query, connection)
dr = cmd.ExecuteReader
If dr.Read() Then
Column0 = dr(0)
End If
connection.Close()

face recognition for home security system

the project is face and pin code recognition for home security system in vb and mysql, the problem is how store face image of users in db for recognizer part, by the way i write the code for it but i dont know whats the problem that cant save images.
this code in public class
Dim ds As DataSet
Dim da As MySqlDataAdapter
Dim dbCon As MySqlConnection
Dim COMMAND As MySqlCommand
Dim dr As MySqlDataReader
this code for add button actually is function
Dim FileSize As UInt32
Dim rawData() As Byte
Dim dbCon As New MySqlConnection("Server = 127.0.0.1; database=database; uid= root; pwd= 6404")
dbCon.Open()
dbCon.ChangeDatabase("psdb")
Dim COMMAND As New MySqlCommand("SELECT actor_pic, filesize, filename FROM actors WHERE actor_name = ?autoid", dbCon )
COMMAND.Parameters.AddWithValue("?autoid", txtname.Text)
dr = COMMAND.ExecuteReader
dr.Read()
'data is in memory
FileSize = dr.GetUInt32(dr.GetOrdinal("filesize"))
rawData = New Byte(FileSize) {}
'get the bytes and filesize
dr.GetBytes(dr.GetOrdinal("actor_pic"), 0, rawData, 0, FileSize)
Dim ad As New System.IO.MemoryStream(100000)
' Dim bm As New Bitmap
ad.Write(rawData, 0, FileSize)
dr.Close()
dbCon.Close()
dbCon.Dispose()
ad.Dispose()
DataGridView1.Rows.Add()
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(0).Value = imagez.ToBitmap
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Height = DataGridView1.Columns(0).Width * 0.75
' the 0.75 * width for the height keeps it at 4:3 aspect ratio, so it looks normal.
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(1).Value = "image" & DataGridView1.Rows.Count - 1

Retrieving Image from Mysql using vb.net

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.

Convert MySQL DataSet to String

I want to check if a user is an administrator or user and I want to change the dataset to a string so I can use it in Label1.
I've tried Using 'GetXML' but it comes in a funny format something like 'Administrator', well it's a bit different to that. I want to be able to use the value of the label1.text for other features in my program.
Here is my code:
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim ServerString As String = "server=localhost;user id=root;password=;database=business elements"
SQLConnection.ConnectionString = ServerString
SQLConnection.Open()
Dim ds As New DataSet()
Dim cmd As New MySqlCommand("SELECT Level FROM users WHERE username = '" & UsernameTextBox.Text & "'", SQLConnection)
Dim da As New MySqlDataAdapter(cmd)
da.Fill(ds)
Dim str As String = ds.GetXml
ds.GetXml()
Label1.Text = str
Try this
Dim str As String = ds.Tables(0).Rows(0).Item(0).ToString()