Thursday, October 8, 2009

Saving images (*.JPG;*.BMP;*.PNG;*.GIF;*.*) to MySql Database

This code excerpt from one of my projects demonstrates how to save an image file like JPEG(*.jpg;*.jpeg;*.jpe;*.jfif); GIF, PNG, BMP or even All Files(*.*) into a Mysql Database server. As of the time of this writing I was using Mysql version 5.1.32

You can visit the following sites for references:



Their is a 'Browse Image' button that calls an OpenFileDialog that filters the images, once the user selected the desired image it will be displayed to the PictureBox.

After it is displayed in the PictureBox you can click on the 'Save' button to save the image to the database.



This is my the code:

------------------------------
Private mImageFile As Image
Private mImageFilePath As String


'From Browse Image button
Private Sub Buttonbrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Buttonbrowse.Click


Try


OpenFileDialogpic.Filter =
"JPEG(*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|GIF(*.
gif)|*.gif|PNG(*.png)|*.png|BMP(*.bmp)|*.bmp|All
Files(*.*)|*.*"


OpenFileDialogpic.ShowHelp = True


OpenFileDialogpic.FilterIndex = 1

OpenFileDialogpic.FileName = ""


If OpenFileDialogpic.ShowDialog = Windows.Forms.DialogResult.Cancel Then

Exit Sub

End If


If System.IO.File.Exists(OpenFileDialogpic.FileName) = False Then
Exit Sub
Else

TextBoxpicture.Text = OpenFileDialogpic.FileName
mImageFilePath = TextBoxpicture.Text

'Display image

mImageFile = Image.FromFile(mImageFilePath)

PictureBoxenrollment.Image = mImageFile
PictureBoxenrollment.Invalidate()
'TextBoxpicture.Invalidate()
End If

Catch ex As Exception
MsgBox(ex.ToString)

End Try

End Sub


'

'From Save button
'Blob image
'
Dim FileSize As UInt32

'Write an image in a stream

Dim fspic As FileStream = New FileStream(mImageFilePath, FileMode.Open, FileAccess.Read)

FileSize = fspic.Length


Dim rawdata() As Byte = New Byte(FileSize) {}


fspic.Read(rawdata, 0, FileSize)

fspic.Close()


mysqlcon.Open()


mImageFile = Image.FromFile(mImageFilePath.ToStri
ng())

Dim save As String = "INSERT INTO enrollment VALUES" & _
"('" & fname & "', '" & mname & "', '" & lname & "', " & age & "," & _ "'" & address & "', '" & gender & "', '" & date_of_birth & "', '" & place_of_birth & "'," & _ "'" & year_level & "', '" & id_no & "', '" & date_enrolled & "', '" & sy_a & "', '" & sy_b & "'," & _ "'" & contact_no & "', '" & parent_ & "', '" & guardian & "', @mImageFile , '" & transfeeree & "'," & _ "'" & date_of_transfer & "','" & transfer_in & "', '" & transfer_out & "')"

Dim cmd As New MySqlCommand(save, mysqlcon)


cmd.Parameters.AddWithValue("@mImageFile", rawdata)

'
'Blob image

cmd.ExecuteNonQuery()

mysqlcon.Close()

MessageBox.Show("Records and Image Saved!", "Save to Database", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button3, MessageBoxOptions.RightAlign, True)













No comments: