如何保存用户图像并将其保留在应用程序文件夹中并显示?

时间:2019-06-09 17:30:08

标签: 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

1 个答案:

答案 0 :(得分:0)

我建议使用Path.Combine来构建路径。
您的应用程序目录由Application.StartupPath返回,您只需要将此路径与选择的子路径结合起来即可在其中引用或创建目录。

然后可以将此路径与OpenFileDialog.SafeFileName(文件名中不包含Path部分)组合,以创建最终的目标Path(尽管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 相同),因此您可以仅将图像文件名存储在数据库中,然后合并具有该路径的文件名。
将此路径分配给字段,然后将其与数据库中存储的任何图像文件名结合使用以访问位图。

相关问题