I have this code to load image from MySql database to picturebox. But it takes about 4-5seconds to load the image.
' this code if for SAVING IMAGE to MySQL database.
Public Function ConvertToBytes(ByVal img As PictureBox) As Byte()
Dim msPic As New MemoryStream
img.Image.Save(msPic, System.Drawing.Imaging.ImageFormat.Bmp)
Dim Mybyte() As Byte = msPic.GetBuffer
Return Mybyte
End Function
' this code if for RETRIEVING IMAGE FROM MySQL database.
sql_connection = New MySqlClient.MySqlConnection(conn.connect)
sql_connection.Open()
Dim arrImage() As Byte
sql_command = New MySqlClient.MySqlCommand("SELECT * FROM tblCatalog WHERE IDCardNo = '" & TEXTBOX1.Text & "'", sql_connection)
sql_command.CommandTimeout = 1000
sql_reader = sql_command.ExecuteReader()
While (sql_reader.Read())
arrImage = sql_reader("Picture")
Dim mstream As New System.IO.MemoryStream(arrImage)
PictureBox3.Refresh()
PictureBox3.Image = Image.FromStream(mstream)
End While
sql_reader.Close()
I place my code into the Timer_tick, I also tried at the button event. But still the result is just the same. Can somebody help me?. I want that when I press enter or click the button, it quickly load the image.
Related
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.
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.
I am using service-based database (.mdf file) to add name and the photo to my database in VS 2010. After debugging and adding the data it adds up into the .mdf but while trying to retrieve it, it doesn't show. It shows only after next debugging. I am really stuck in this for 2 days please help me.
Thank you in advance.
Connection string I am currently using :
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=" & path & "Database1.mdf;Integrated Security=True;User Instance=True")
This is the code I am using to save the image and name :
Dim cmd As New SqlCommand("INSERT INTO Information VALUES(#name,#photo)", con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)
And this is the code I am using to display data in the datagridview
Me.InformationTableAdapter.Fill(Me.Database1DataSet.Information
i m working on a project , though m not a programming student so dont know much about it
i have saved images and links in my database
but i want to retrieve all of them on my app collecively ( like one image with its associated site's link) such that user can look at image and if he wants to go to the site associated with the image, he can click on the link or button (but image and links retriving at same time )
or is there any way that buttons generate autometically according to the images retrieved ???
"im posting this just becoz its mandatory to post what you have tried" so copying from somewhere
Dim conn As New MySqlConnection
conn.ConnectionString = ConnectionString
Dim cmd As New MySqlCommand
cmd.Connection = conn
conn.Open()
cmd.CommandText = "SELECT Foto FROM MyTable WHERE ID = '" & IDtxt.ToString & "'"
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
If (IsDBNull(reader("Foto"))) Then
frmCartaIdentitaView.pctImage.Image = Nothing
Else
Dim byteImage() As Byte = reader("Foto")
Dim frmImageView stmFoto As New System.IO.MemoryStream(byteImage)
frmImageView.pctImage.Image = Image.FromStream(stmFoto)
frmImageView.pctImage.SizeMode = PictureBoxSizeMode.Zoom
frmImageView.Show()
End If
End While
I have a vb.net program that tries to take a bunch of images and change the resolution to a smaller size. My program tries to loop through all the images to accomplish this using this code below. I've posted both the function and the button click that calls it. It will go through 27 images fine but on the 28th will error out with "parameter is not valid".
Friend Shared Function SetResolution(ByVal sourceImage As Image, ByVal resolution As Integer, ByVal strFullPath As String) As Image
Try
Dim reduction As Double = resolution / CInt(sourceImage.HorizontalResolution)
Using newImage As New Bitmap(sourceImage.Width, sourceImage.Height, sourceImage.PixelFormat)
newImage.SetResolution(resolution, resolution)
Dim outImage As New Bitmap(sourceImage, CInt(sourceImage.Width * reduction), CInt(sourceImage.Height * reduction))
Using g As Graphics = Graphics.FromImage(newImage)
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
g.DrawImage(outImage, 0, 0)
g.Dispose()
End Using
newImage.Dispose()
Return outImage
End Using
Catch ex As Exception
MsgBox("An error occurred with the SetResolution function - " & ex.Message)
End Try
End Function
Private Sub btnSaveImages_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveImages.Click
Dim S As String
Dim Box As MsgBoxResult = MsgBox("Any previous images saved to this location will be overwritten. Are you sure you want to save these images?", MsgBoxStyle.YesNo)
Dim strFolderPath As String = ""
Dim strFolderReportPath As String = txtBrowse.Text & "\Report"
'Try
'the Report folder may not exist. Create it if needed.
If Not Directory.Exists(strFolderReportPath) Then
Directory.CreateDirectory(strFolderReportPath)
Else
'if it does exist then we need to either delete the folder or clean out all the files.
Dim downloadedMessageInfo As System.IO.DirectoryInfo = New DirectoryInfo(strFolderReportPath)
For Each file As FileInfo In downloadedMessageInfo.GetFiles()
file.Delete()
Next
For Each dir As DirectoryInfo In downloadedMessageInfo.GetDirectories()
dir.Delete(True)
Next
End If
If Box = MsgBoxResult.Yes Then
If lstSelectedImages.Items.Count <> 0 Then
For Each S In lstSelectedImages.Items
'MessageBox.Show(S)
Dim image1 As Image = Image.FromFile(S)
Dim strFilePath As String = Path.GetDirectoryName(S)
strFolderPath = Path.GetDirectoryName(S)
Dim strFileName As String = Path.GetFileName(S)
Dim strNewFolder As String = strFilePath & "\Report\"
strFileName = strFileName.Replace(".", "-Report.")
Dim strFullPath As String = strFilePath & "\Report\" & strFileName
image1 = SetResolution(image1, 50, strFilePath & "\" & Path.GetFileName(S))
'the Report folder may not exist. Create it if needed
If Not Directory.Exists(strNewFolder) Then
Directory.CreateDirectory(strNewFolder)
End If
image1.Save(strFullPath, System.Drawing.Imaging.ImageFormat.Jpeg)
image1.Dispose()
image1 = Nothing
Next
Dim di As New DirectoryInfo(strFolderReportPath)
'PopulateReportViewer(lstSelectedImages)
PopulateReportViewerByDir(di)
lblImageFolderLocation.Text = "Image Location: " & strFolderReportPath
MsgBox("Images saved to " & strFolderReportPath)
Else
MsgBox("Please select images to be saved into the Selected Images list box", MsgBoxStyle.Information)
End If
Else
End If
tbSelectCompressImages.TabPages.Add(TabPage2)
tbSelectCompressImages.SelectedIndex = 1
'Catch ex As Exception
' MsgBox("An error occurred with the Save Images button - " & ex.Message)
'End Try
End Sub
So, I was pretty stumped with that and decided to make a small change to how the bitmap was created to below. I was able to get 28 images saved again but this time received an out of memory error for the Graphics.FromImage line.
Dim newimage As Bitmap = DirectCast(Image.FromFile(strPath), Bitmap)
Does anyone know why this is occurring looking at my code. Or, is there code somewhere that I can get to set the resolution for an image so that the memory stamp is much smaller?
thanks.
but we can't see what you do with sourceImage and outImage.
image1 = SetResolution(image1, 50, strFilePath & "\" & Path.GetFileName(S))
You are re-assigning the image1 variable with this statement. Problem is, you never disposed the original image1. It is also a major guess why you are passing a path name, the method doesn't use it at all. So somewhat more sane code that doesn't forget to dispose ought to look like this:
Dim newImage = SetResolution(image1, 50)
image1.Dispose()
image1 = newImage