vb.net - 如何保存用户图像并将其保存在我的应用程序文件夹中并显示它?
问题描述
我正在尝试在 PictureBox 中显示图像。
用户输入他/她的照片,我将其复制到应用程序文件夹(“图像”)。当我尝试显示“图像”文件夹中的路径时,它总是返回空的。
picturepath
是我用来在我的数据库中存储路径的变量。
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
PicturePath = "/images/" + correctfilename
FileToCopy = openFileDialog1.FileName
NewCopy = "C:\Users\nilraj\source\repos\caloriecal\caloriecal\Images\sss.jpg"
path = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10))
correctfilename = System.IO.Path.GetFileName(openFileDialog1.FileName)
System.IO.File.Copy(FileToCopy, path + "/Images/" + correctfilename)
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
TextBoxPictureFilePath.Text = ""
img = openFileDialog1.FileName
PictureBox1.Image = System.Drawing.Bitmap.FromFile(img)
TextBoxPictureFilePath.Text = openFileDialog1.FileName
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
解决方案
我建议使用Path.Combine来构建你的路径。
您的应用程序目录由Application.StartupPath返回,您只需将此路径与选择的子路径组合起来即可在此处引用或创建目录。
然后,您可以将此路径与OpenFileDialog.SafeFileName(没有路径部分的文件名)组合,以创建最终目标路径(事件虽然Path.Combine
可以一次组合两个以上的组件,但这里没有文件名的路径是用于验证目标目录是否存在,如果不存在,则创建它。您可以将此代码移动到其他地方)。
请注意,我在OpenFileDialog
这里使用的是一个类,而不是 Control。如果需要,您可以ofd
用您的对象替换该对象openFileDialog1
。
请记住过滤您要处理的图像类型。
Dim ofd = New OpenFileDialog()
If ofd.ShowDialog() <> DialogResult.OK Then Return
Try
Dim saveFilePath = Path.Combine(Application.StartupPath, "Images")
If Not Directory.Exists(saveFilePath) Then Directory.CreateDirectory(saveFilePath)
Dim saveFileName = Path.Combine(saveFilePath, ofd.SafeFileName)
File.Copy(ofd.FileName, saveFileName, True)
PictureBox1.Image?.Dispose()
PictureBox1.Image = New Bitmap(saveFileName, True)
TextBoxPictureFilePath.Text = ofd.FileName
Catch IOEx As IOException
MessageBox.Show("Cannot read file from disk. Original error: " & IOEx.Message)
Finally
ofd.Dispose()
End Try
如果VB.Net
正在使用的版本不处理此语法:PictureBox1.Image?.Dispose()
,请使用:
If PictureBox1.Image IsNot Nothing Then PictureBox1.Image.Dispose()
由于您的图像将位于相同的相对路径中(与此处[Application.StartupPath]\Images
相同saveFilePath
),您可以将图像文件名存储在数据库中,然后将文件名与此路径结合起来。
将此路径分配给字段,然后将其与存储在数据库中的任何图像文件名组合以访问位图。
推荐阅读
- javascript - Gatsbyjs 谷歌分析 gdpr
- javascript - Express 上的 GET/POST 方法
- javascript - 木偶表演者无头行为不同
- javascript - JSON、特殊字符和发送到数据库
- java - 获取 Maven 依赖项的连接重置
- javascript - JavaScript:返回 null 的类
- excel - 概述来自多个来源的一个单元格中的文本
- r - geom_bar() 和 geom_col() 的所有位置是什么?
- design-patterns - OLAP 多维数据集设计:运行时生成的度量
- javascript - 警告控制台:列表中的每个子项都应在代码 react.js 中的表中具有唯一的“键”道具