使用拖放获取图像位置

Get image location using a drag and drop

我有一个拖放事件,可以将图像放入图片框中。我需要将图像位置获取到字符串以存储在我的数据库中。如果我使用 OpenFileDialog,我可以获得位置,但如果我使用拖放,我似乎无法获得它。这是我的代码:

    Private Sub picCategoryImage_DragEnter(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragEnter


    'Procedure to copy the dragged picture from the
    'open window

    If e.Data.GetDataPresent(DataFormats.FileDrop) Then

        'If the file explorer is open, copy the picture to the box
        e.Effect = DragDropEffects.Copy
        picCategoryImage.BorderStyle = BorderStyle.FixedSingle
        TextBox1.Text = picCategoryImage.ImageLocation

    Else

        'otherwise, don't take action
        e.Effect = DragDropEffects.None
        btnDeleteImage.Visible = False

    End If


End Sub

Private Sub picCategoryImage_DragDrop(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragDrop

    'Procedure to select the pictue and drag to picturebox
    Dim picbox As PictureBox = CType(sender, PictureBox)
    Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())

    If files.Length <> 0 Then

        Try

            picbox.Image = Image.FromFile(files(0))
            btnDeleteImage.Visible = True
            picbox.BorderStyle = BorderStyle.None
            picCategoryImage.BringToFront()
            btnDeleteImage.BringToFront()


        Catch ex As Exception

            MessageBox.Show("Image did not load")

        End Try

    End If

End Sub

根据 Plutonix 的建议,您已经在使用文件路径,所以您已经知道了。这就是 Image.FromFile 能够从文件创建 Image 的方式。如果您的意思是您需要稍后能够获取路径,那么您有两个主要选择:

  1. 照你做的做,将路径存储在成员变量中以备后用。

  2. 不调用Image.FromFile并设置PictureBoxImage,只调用PictureBoxLoad方法.然后,您可以从 ImageLocation 属性.

  3. 获取路径

我实际上建议无论如何都使用选项 2,因为它具有不会像当前代码那样锁定文件的额外优势。