如果用户选择图像,它将按照以下代码保存图像:
PictureBox1.Image.Save(PicFile, System.Drawing.Imaging.ImageFormat.Jpeg)
现在,如果用户决定不选择图像,是否有办法跳过此代码?我目前收到以下错误:
附加信息:未将对象引用设置为对象的实例。
这是我尝试过的:
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
答案 0 :(得分:0)
现在,如果用户决定不选择图像,是否有办法跳过此代码?
如果你这意味着用户选择取消,那么是。只需将Try[...]Catch
块放入If
语句中,只有当用户选择打开时,它才会尝试代码。
这样的事情:
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
如果您只想跳过某些代码,可以查看opf.FileName
。举个例子:
If opf.FileName <> "" Then
PictureBox1.Image = Image.FromFile(opf.FileName)
End If