how to update image using database in vb.net - vb.net

what is the problem of this code?? i got a error for the GDI+ and i dont know to solve.
Private Sub saveEmployee()
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)--i got error in this line..A generic error occurred in GDI+.
Dim arrPic() As Byte = ms.GetBuffer()
Dim cmdEmp As New MySqlCommand
Dim sqlEmp As String
sqlEmp = "update tbl_employee set emPic=#emPic where emID='" & lbl_empID.Text & "'"
With cmdEmp
.Parameters.AddWithValue("#emPic", arrPic)
.ExecuteNonQuery()
End With
End Sub

Try replacing that line with this :
Dim bm as Bitmap = new Bitmap(PictureBox1.Image)
bm.Save(ms, PictureBox1.Image.RawFormat)
The reason could be that the Image is being used by the PictureBox. Its also good practice to have the following instead :
Using ms As MemoryStream = New MemoryStream()
Dim bm as Bitmap = new Bitmap(PictureBox1.Image)
bm.Save(ms, PictureBox1.Image.RawFormat)
Dim arrPic() As Byte = ms.GetBuffer()
Dim cmdEmp As New MySqlCommand
Dim sqlEmp As String
sqlEmp = "update tbl_employee set emPic=#emPic where emID=#emID"
With cmdEmp
.Parameters.AddWithValue("#emPic", arrPic)
.Parameters.AddWithValue("#emID", int.Parse(lbl_empID.Text))
.ExecuteNonQuery()
End With
End Using
This way the MemoryStream will get Disposed after being used. And adding #emID as a parameter is safer.

RESOLVED!!!
Bind picture box to the datasource field using the Advance tab in the DataBindings section. Use the ImageLocation property instead of image. Then change the Update mode to NEVER. but how abt the update ??? Use a textbox and hide behind the Picture box [with visible = true]. Bind textbox to same datasource. THAT IS!!!
image displays directly in picture box whilst the textbox TextChanged property handles whether there is UPDATE or Not. took me a while but it works fine now. good luck as u code... ~ SAM, GHANA

Related

Insert & receive picture from ms access query db vb.net

so, I want to insert a picture to my ms-access DB and it works fine.
inserting code :
Dim ms As New System.IO.MemoryStream
Dim bmpImage As New Bitmap(GunaPictureBox1.Image)
bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
bytImage = ms.ToArray()
ms.Close()
Dim d As New DBConnect
d.Editdata(String.Format("INSERT INTO TeachersTable (TeacherFN, TeacherLN, [TeacherImage]) values('{0}','{1}','{2}')", GunaTextBox1.Text, GunaTextBox2.Text, bytImage))
display code :
Dim dt As DataTable = New DBConnect().selectdata(String.Format("SELECT [TeachersTable.TeacherImage] FROM TeachersTable where TeachersTable.ID= {0}", 1))
Dim EditTeacher As New EditTeacher
Dim pictureData As Byte() = DirectCast(dt.Rows(0)(1), Byte())
Dim stream As New IO.MemoryStream(pictureData)
EditTeacher.GunaPictureBox1.Image = Image.FromStream(stream)
EditTeacher.Show()
but now I want to display it on a picture box but when I execute the code its shows me an error said "Parameters is not valid" & I don't know where is the problem!

Show image in vb.net

I'm trying to show a saved image in SQL Server but it gives me an error that says "parameter is not valid".
While oDataReader.Read()
TextBox1.Text = oDataReader("nombre")
Dim imagenbyte As Byte()
imagenbyte = oDataReader("imagen")
Dim mStream As New IO.MemoryStream()
mStream.Write(imagenbyte, 0, Convert.ToInt32(imagenbyte.Length))
Dim bm As Bitmap = New Bitmap(mStream, True)
PictureBox1.Image = bm
End While
You can consolidate that code down to this:
While oDataReader.Read()
TextBox1.Text = oDataReader("nombre")
Dim mStream As New IO.MemoryStream(oDataReader("imagen"))
PictureBox1.Image = Image.FromStream(mStream)
End While
The main fix here is using Image instead of Bitmap. And if you know you'll only have one record, you should change While to If. If you might have more than one record, you need to completely re-think some things in your user interface.

Check if image column is Null VB.NET

Good Day everyone. I need help with my code below.
Dim stream As New MemoryStream()
connect()
Dim command As New SqlCommand("SELECT image FROM tblHouseholdMembers WHERE id= '" & lvmem.FocusedItem.Text & "'", cn)
Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte()) --> 'Error message of null image
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)
pbProfilePic.Image = bitmap
I want to put a messagebox to identify if it's null before the error cast.
Instead of using the DirectCast method, use the TryCast and then check if the casting result is nothing:
Dim image As Byte() = TryCast(command.ExecuteScalar(), Byte())
if image isnot nothing then
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)
pbProfilePic.Image = bitmap
else
'Error message here
end if
The way to directly test if a field coming back from a database is null is:
if ValueFromDb is System.DbNull.Value then
' whatever you want to do in that case
Something that really confused me when I was first learning VB is that a null value from a DB read is NOT equal to Nothing. It is not Nothing, it is System.DbNull.Value.
Most of my projects these days, I write a little function I call "denull" that says something like:
public shared function denull(value as object, defalt as object)
if value is system.dbnull.value then
return defalt
else
return value
end function
Then I wrap every value I read from the db in this function. This saves a lot of code.
for each row in mydataset.tables(0).rows
foo=denull(row("foo"),"")
bar=denull(row("bar"),0)
plugh=denull(row("plugh"),nothing)
... etc ...

Digital Person fingerprint image retrieving

I am using the following code to save the finger print scanned through Digital Persona's device.
Dim cls As New ClsDataAccess
Dim con = New SqlConnection(cls.SqlConnectiontring)
Dim cmd As New SqlCommand
Dim str As New MemoryStream
Enroller.Template.Serialize(str)
Dim serializedTemplate As Byte() = str.ToArray()
'cmd.Parameters.Add(New SqlParameter("#fn", SqlDbType.VarChar, 10)).Value = "Joe"
'sql.DbType
Dim param(0) As SqlParameter
'Dim t As Integer = Join(serializedTemplate, ",")
param(0) = New SqlParameter("#biometricData", serializedTemplate)
'Public OnlineConnectionString As String = "Data Source = 203.234.5.678; Database = mydb; User CndID = username; Password = xxxxxx;"
'Dim cmd As New SqlCommand("Insert Into tbltestbio (biovalue) Values (#biometricData)", con)
'cmd.Parameters.Add(param)
Dim pictureParameter As SqlClient.SqlParameter = New SqlClient.SqlParameter("#Picture", SqlDbType.Binary)
pictureParameter.Value = serializedTemplate
cmd.Parameters.Add(pictureParameter)
The problem is that when I try to retrieve the image using memory stream like an ordinary image, it won't load. Any other image using my Object Browser is being displayed by this code. What am I doing wrong? Below is the code for image retrieval.
Sub ImageLoadFun(ByVal barrImg() As Byte)
Try
Dim ms As New MemoryStream(barrImg)
Dim returnImage As Image = Image.FromStream(ms)
PictureBox1.Image = returnImage.Image
EmployeeDrawPicture(img)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
It seems you get "template" from sensor and not "image".
Template is a list of minutiae and other info.
You need to check in your FingerPrint API if there's method to get image.
Be careful, usually image, from fingerprint sensor, is not in RGB format but in greyscale.

Loop through each row, create button for each record. Cannot get image from database

I have a form that I am trying to populate with a control for each item on my database (SQLCe). Problem is that one of the items I am trying to return from the database is an image. However, my original code gave me an error:
Value of type "Byte' cannot be converted to 'System.Drawing.Image'
Here is my original code
Private Sub btnCategories_Click(sender As Object, e As EventArgs) Handles btnCategories.Click
Dim dt As DataTable = ProducT_CATEGORYTableAdapter.GetData
For Each row As DataRow In dt.Rows
Dim btn As New btnCategoryTabs()
btn.lblCategoryName.Name = DirectCast(row("Category_Name"), String)
btn.lblCategoryName.Text = btn.lblCategoryName.Name
btn.picPCategoryPicture.Image = DirectCast(row("Image"), Byte) 'Error Here'
'Add categories to the Panel
flpMainPanel.Controls.Add(btn)
Next
End Sub
I am sure that I have to convert the image, so I started messing around with this bit of code:
Dim Stream As New MemoryStream()
Dim image As Byte() = CType('Can't figure out what to put here), Byte())
Stream.Write(image, 0, image.Length)
Dim bitmap As New Bitmap(Stream)
Any help will be appreciated.
Thanks.
If you have stored image data in your database then it would be a Byte() i.e. and array, not just a single Byte. You then have to convert that Byte array to an Image. You're on the right track. Here's one I prepared earlier:
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection)
connection.Open()
Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
connection.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.'
picture = Image.FromStream(stream)
End Using
http://www.vbforums.com/showthread.php?469562-Saving-Images-in-Databases&highlight=
In your case specifically, that becomes:
'Create a stream in memory containing the bytes that comprise the image.'
Using stream As New IO.MemoryStream(DirectCast(row("Image"), Byte()))
'Read the stream and create an Image object from the data.'
btn.picPCategoryPicture.Image = Image.FromStream(stream)
End Using