VB NET check SQL server image data type for null or empty - sql-server-2012

I need to check for null value of SQL server image data type ,
here is my code :
Dim cmd As New SqlCommand("select id_image1 from work_tbl where
work_id = 12345 ", conn)
Dim stream As New MemoryStream()
conn.Open()
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
stream.Write(image, 0, image.Length)
conn.Close()
Dim bitmap As New Bitmap(stream)
picturebox1.Image = bitmap
I need to stop the procedure with msgbox if my image column is empty .

Dim cmd As New SqlCommand("select id_image1 from work_tbl where
work_id = 12345 ", conn)
Dim stream As New MemoryStream()
conn.Open()
if DBNull(cmd.ExecuteScalar())=false
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
stream.Write(image, 0, image.Length)
Dim bitmap As New Bitmap(stream)
picturebox1.Image = bitmap
end if
conn.Close()

Related

Added collection of images from SQL datareader on ItextSharp

I need to get a collection of images from a datareader or even from a datatable (if recommended to use this) of sql.
My intent is to populate the cell with the variable "myimage" (and I succeed perfectly)
In the variable "myimage2" I would like to insert the collection of images obtained from a datareader or a datatable, what can I do?
Currently I can insert only one image using the "getvalue" method as written in the code.
Dim connessione As New SqlConnection
Dim comando As New SqlCommand
connessione.ConnectionString = stringa_database
connessione.Open()
comando = connessione.CreateCommand()
comando.CommandType = CommandType.Text
comando.CommandText = "SELECT u.id_nota, u.immagine From immagini_aggiuntive u INNER JOIN note q ON q.id = id_nota where id_nota= " & id
Dim lettura As SqlDataReader = comando.ExecuteReader()
lettura.Read()
Dim imageByte2 As Byte() = CType(lettura.GetValue(1), Byte())
Dim ms2 As New MemoryStream(imageByte2, 0, imageByte2.Length)
Dim myImage2 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(ms2)
'fine blocco
Dim imageByte As Byte() = CType(row.Cells(11).Value, Byte())
Dim ms As New MemoryStream(imageByte, 0, imageByte.Length)
Dim myImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(ms)
Dim cellimg As PdfPCell = New PdfPCell()
cellimg.AddElement(myImage)
cellimg.AddElement(myImage2)
pdfTable.AddCell(cellimg)
lettura.Close()
connessione.Close()

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!

When I try to pull nvarchar column value that has an emojis stored in it, the data in VB.net it displays as '??'

When I try to pull the emoji value from the database using VB.net the emoji is displayed as '??'
Is there some sort of conversion I need to do in my stored procedure?
Private Function DisplayEmoji(input As String) As String
Dim output As New StringBuilder()
Dim enumerator = StringInfo.GetTextElementEnumerator(input)
While enumerator.MoveNext()
Dim chunk As String = enumerator.GetTextElement()
If Char.IsSurrogatePair(chunk, 0) Then
output.Append("<img src=""" + "https://abs.twimg.com/emoji/v1/72x72/" + Char.ConvertToUtf32(chunk, 0).ToString("x") + ".png"" style=""height:1.5em; width:1.5em;"">")
Else
output.Append(chunk)
End If
End While
Return output.ToString()
End Function
Or insert your image Blob type and read sql.
Dim filePath As String = Server.MapPath("APP_DATA/test.png")
Dim filename As String = Path.GetFileName(filePath)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
Insert to Database yor image
Dim strQuery As String = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = "image/png"
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
InsertUpdateData
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.
ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function

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.

How to add image from database to PictureBox?

I am using this to get image bytes from the database
cmd.CommandText = "select imagedate from projectimages where imagename = '" + _
ListBox1.Text + "' and CSVprojectref=checksum('" + textboxFileRef.Text + "')"
Dim img As Object = cmd.ExecuteScalar()
Now how can I add this to PictureBox.image. I am having a lot of trouble retrieving the image and displaying it in the PictureBox.
The datatype is Image in sql database and i use this code to save image to db
Dim ms As New IO.MemoryStream
If imageFilename.Contains("jpeg") Or imageFilename.Contains("jpg") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
If imageFilename.Contains("png") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End If
If imageFilename.Contains("gif") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
End If
If imageFilename.Contains("bmp") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
End If
Dim bytes() As Byte = ms.ToArray
Dim img As String = Convert.ToBase64String(bytes)
Dim cmd As New OleDb.OleDbCommand("insert projectimages values('" + imageNameTemp + "','" + img + "',CHECKSUM('" + textboxFileRef.Text + "'))", con)
cmd.ExecuteNonQuery()
After 5-6 hours of searching forums and blogs and everything i fond this... to save image to database
1- datatype should be image in database
Now add this code when storing image to the sql database
OpenFileDialog1.ShowDialog()
imageFilename = OpenFileDialog1.FileName
Dim imageUpload As Image
imageUpload = Image.FromFile(OpenFileDialog1.FileName)
If imageFilename <> "" Then
Dim imageNameTemp As String
imageNameTemp = imageFilename
While (imageNameTemp.Contains("\"))
imageNameTemp = imageNameTemp.Remove(0, imageNameTemp.IndexOf("\") + 1)
End While
Dim ms As New IO.MemoryStream
If imageFilename.Contains("jpeg") Or imageFilename.Contains("jpg") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
If imageFilename.Contains("png") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End If
If imageFilename.Contains("gif") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
End If
If imageFilename.Contains("bmp") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
End If
'Dim cmd As New SqlCommand("INSERT INTO projectimages (imagename,imagedate,csvprojectref) VALUES ('" + imageFilename + "',#BLOBData,CHECKSUM('" + textboxFileRef.Text + "'))", con)
Dim b() As Byte = ms.ToArray()
Dim cmd As New SqlCommand("INSERT INTO projectimages (imagename,imagedate,csvprojectref) VALUES ('" + imageNameTemp + "',#BLOBData,CHECKSUM('" + textboxFileRef.Text + "'))", con)
cmd.Parameters.Add("#BLOBData", SqlDbType.Image, b.Length).Value = b
' Dim cmd As New SqlCommand("insert projectimages(imagename,imagedate,csvprojectref) values('imagma','" + img + "',CHECKSUM('" + textboxFileRef.Text + "'))", con)
cmd.ExecuteNonQuery()
' cmdTemp.Parameters.Add("#photo", SqlDbType.Image, b.Length).Value = b
End If
And when to retrieve data to insert into picture box use this code...
cmd.CommandText = "select imagedate from projectimages where imagename = '" + ListBox1.Text + "' and CSVprojectref=checksum('" + textboxFileRef.Text + "')"
cmd.Connection = con
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
Dim bytBLOBData() As Byte = _
ds.Tables(0).Rows(c - 1)("imagedate")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox1.Image = Image.FromStream(stmBLOBData)
End If
Use a MemoryStream object as per Microsoft.
Dim img As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
Dim ms as MemoryStream = New MemoryStream(img)
pictureBox.Image = Image.FromStream(ms)
assuming imagedate field a blob field.
here's my code to show blob file to picturebox in vb.net. hope it helps
Dim connstring As String = "Database=pmk;data source=localhost;user id=root;password="
Dim Sql As String = "select * from mastermahasiswa where Nim='" & TextBox1.Text & "'"
Dim conn As New MySqlConnection(connstring)
Dim cmd As New MySqlCommand(Sql, conn)
Dim dr As MySqlDataReader = Nothing
conn.Open()
dr = cmd.ExecuteReader()
dr.Read()
Dim imagebytes As Byte() = CType(dr("Foto"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()
I was getting the parameter not valid error as well. To fix, I added a picturebox to my form that loads the image I'm copying to the SQL server as a background image. This statement seems to be key:
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
It makes the actual upload take a lot longer, but I'm no longer getting the parameter error... I think because the pictures are actually valid images now.
SSScmd.CommandText = "INSERT INTO PreviewSlideshow (Name, Photo) VALUES (#name, #photo)"
Dim p As New SqlParameter("#photo", SqlDbType.Image)
For Each CurFile As IO.FileInfo In New IO.DirectoryInfo(sSourcePath).GetFiles
If CurFile.Name = "Thumbs.db" Then
'skip
Else
If CurFile.Extension = "jpg" Or CurFile.Extension = "png" Then
'show the image name on the form
ImageName.Text = CurFile.Name
SSScmd.Parameters.AddWithValue("#name", ImageName.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage = Image.FromFile(sSourcePath & CurFile.Name)
PictureBox1.BackgroundImageLayout = ImageLayout.Stretch
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
p.Value = data
SSScmd.Parameters.Add(p)
SSScmd.ExecuteNonQuery()
SSScmd.Parameters.Clear()
End If
End If
Next