If a user selects an image it will save the image as per the below code:
PictureBox1.Image.Save(PicFile, System.Drawing.Imaging.ImageFormat.Jpeg)
Now if the user decides not to select an image, is there a way to skip this code? I currently get the following error:
Additional information: Object reference not set to an instance of an object.
This is what I've tried:
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(.jpg;.png;*.gif)|*.jpg;*.png;*.gif"
If opf.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(opf.FileName)
End If
Try
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim img As Byte()
img = ms.ToArray()
DataGridView1.Rows.Add(img)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
Now if the user decides not to select an image, is there a way to skip this code?
If by this you mean the user selects Cancel, then yes. Simply place the Try[...]Catch block into your If statement and it will only attempt the code if the user selects Open.
Something like this:
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(.jpg;.png;*.gif)|*.jpg;*.png;*.gif"
If opf.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(opf.FileName)
Try
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim img As Byte()
img = ms.ToArray()
DataGridView1.Rows.Add(img)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
End If
If you only wanted to skip certain bits of code you could do a check on opf.FileName. As an example:
If opf.FileName <> "" Then
PictureBox1.Image = Image.FromFile(opf.FileName)
End If
Related
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.
I'm almost done with my system. All I need to finish is the print process. Sadly, the print dialog is not appearing.
Here's the code for the printing process
Private Sub PrintReceipt()
Dim printdialog As New PrintDialog
Dim printdocument As New Printing.PrintDocument
printdialog.Document = printdocument
AddHandler printdocument.PrintPage, AddressOf printdocument_printPage
Dim result As DialogResult
If (result = DialogResult.OK) Then
printdocument.Print()
End If
End Sub
There is nothing wrong with the printdocument_printpage, which is basically just what it will be printing, yet, since printing hasn't even begun, I won't bother putting it here unless requested.
I want the said dialog to appear after the transaction has been saved. which its not doing for some reason. And here's the code for the save transaction.
Dim payment As New Payment
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
If e.PaymentSuccess = True Then
Try
mydbcon.Open()
Dim Query As String
Query = "select * from itemstored"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
While reader.Read
insertTranscation(reader.GetString("itemname"), reader.GetString("price"))
End While
DeleteItemStored()
PrintReceipt()
reader.Close()
reader.Dispose()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.StackTrace)
End Try
End If
Ignore the mysql here. It's not the main problem.
The dialog will not show if you don't tell it to. You've forgotten to call printdialog.ShowDialog() in your code, and you also never set result to anything before checking it.
It's a simple fix:
Dim result As DialogResult = printdialog.ShowDialog()
I'm trying to:
1) Scan an image and insert it to a memorystream.
2) Show it in picturebox1.
3) Read picturebox1 image into memorystream and save it to oledb.
here's my code :
1st) Scanning by WIA Dialog and inserting image to memorystream then showing it in picturebox1:
Try
Dim CD As New WIA.CommonDialog
Dim F As WIA.ImageFile = CD.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType)
If F IsNot Nothing Then
Dim MStream As IO.MemoryStream = Nothing
Try
'Convert the raw scanner output into a byte array
Dim ImageBytes() As Byte = DirectCast(F.FileData.BinaryData, Byte())
'Read the image data bytes into a MemoryStream
MStream = New IO.MemoryStream(ImageBytes)
PictureBox1.Image = System.Drawing.Image.FromStream(MStream)
Catch ex As Exception
MsgBox("An error occurred: " & ex.Message, MsgBoxStyle.Critical)
End Try
If MStream IsNot Nothing Then MStream.Dispose()
End If
Catch ex As Exception
MsgBox(ex.message, MsgBoxStyle.Critical)
End Try
This is working perfectly.
The problem is coming,
2nd) Reading image from picturebox1 into new memorystream then save it to oledb:
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = connstring
conn.Open()
'Reading image from picturebox1 and then insert it to a new memorystream.
Dim arrImage() As Byte
Dim myMs As New IO.MemoryStream
PictureBox1.Image.Save(myMs, System.Drawing.Imaging.ImageFormat.Jpeg)
arrImage = myMs.GetBuffer
'Now save image to oledb from the memorystream.
Dim query As String = "INSERT INTO Guestinfo ([IDImage]) VALUES (#IDImage)"
Dim command As New OleDbCommand
With command
.CommandText = query
.Parameters.Add("#IDImage", OleDb.OleDbType.Binary).Value = arrImage
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("Saved Successfully!", MsgBoxStyle.Information)
conn.Close()
ListView1.Items.Clear()
loadlistview()
Me.Close()
End If
Error is on this line :
PictureBox1.Image.Save(myMs, System.Drawing.Imaging.ImageFormat.Jpeg)
I might see that this error because during the scanning process we were converting the image into byte array to put it into memorystream, but while reading process we were trying to read the picturebox image as Jpeg into memorystream.
I can see it's complicated for me as a beginner in visualbasic any help would be appreciated.
Per the documentation for Image.FromStream, the stream must be kept open for the lifetime of the Image, but you are disposing of the stream in this line:
If MStream IsNot Nothing Then MStream.Dispose()
Try removing that line from your first code block.
I suppose the MemoryStream should be disposed of at some point, but perhaps the PictureBox and Image classes will take care of that for you. Otherwise, you may have to add a Dispose call when the form is closed.
I recently wrote some code related to a menu strip bar, there is an option contains OpenFile, SaveFile and Exit etc. Following is the code.
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Try
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
Dim sw As New StreamWriter(myStream)
sw.Flush()
sw.Close()
myStream.Close()
End If
Catch Ex As Exception
MessageBox.Show("Can't save file on disk: " & Ex.Message)
End Try
End If
another chunk of code exactly same but withou If statement, as following,
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
Try
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
Dim sw As New StreamWriter(myStream)
'some sw.WriteLine code here...
sw.Flush()
sw.Close()
myStream.Close()
End If
Catch Ex As Exception
MessageBox.Show("Can't save file on disk: " & Ex.Message)
End Try
The problem I have is the second piece of code, when it runs the system will throw out index out of range exception, How can I fix it without using a If statement? Is there any method to show the dialog window anyway? Anyone can give me clue on this index error message? Thanks!
Looking at the source code of OpenFile reveals the possible point of error
public Stream OpenFile()
{
IntSecurity.FileDialogSaveFile.Demand();
string str = base.FileNamesInternal[0];
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException("FileName");
}
Stream stream = null;
new FileIOPermission(FileIOPermissionAccess.AllAccess, IntSecurity.UnsafeGetFullPath(str)).Assert();
try
{
stream = new FileStream(str, FileMode.Create, FileAccess.ReadWrite);
}
finally
{
CodeAccessPermission.RevertAssert();
}
return stream;
}
It seems that the code try to get the base.FileNamesInternal[0]; but if you don't show the dialog or choose a file name to save this internal array is probably empty.
I have tried to read the item at index zero in the property FileNames and I get the same error
string file = saveFileDialog1.FileNames(0) ' Index out of range....
I would like to hear from our WinForms more experienced posters if this is really what it seems
I guess I'm a bit confused about what you are trying to accomplish.
In the second example it seems you never 'show the dialog' ie saveFileDialog1.ShowDialog()
Thus the user cannot select a file/path
Then you attempt to use the file/path that has not been set
http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.openfile.aspx
If you just need to open an arbitrary file for write without showing the user the dialog why not just use File.Open() or something?
http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx
I am currently having problems in storing the contents of any selected notepad file from openFileDialog to the FileStream. My code states a default filename as i do not know how to revise the FileStream code, i want it to register the filename of my selected notepad.
By default it would only read the contents of "messages.txt", i want to have a freedom to choose any notepad file and retrieve the data from it. Any kind of help or advice will do thanks in advance.
here is my code:
Dim Stream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
'i need to do something about this line above
Dim sReader As New System.IO.StreamReader(Stream)
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub
I rearranged your code just a bit. Basically you were creating a stream, and then creating the reader for the stream to "messages.txt". Later you set the stream object to a new stream based on the OpenFile method of the file open dialog. But your reader was still pointing to the first stream you opened, so that is what was getting read. I've changed the code below to not open that first stream, and to create the reader after you have created the stream based on the file the user selected.
'don't create a stream hear and the reader, because you are just recreating a stream later in the code
Dim Stream As System.IO.FileStream
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'This line opens the file the user selected and sets the stream object
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
'create the reader here and use the stream you got from the file open dialog
Dim sReader As New System.IO.StreamReader(Stream)
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub