Solved

How to drop and/or image or image file onto form

Posted on 2011-09-16
8
269 Views
Last Modified: 2013-12-17
I have a .Net 4 Windows Forms project created with Visual Studio 2010 using c#.

I have a form which I would like to be able to drag and drop an image onto to be displayed and saved to a file.  This will allow the user to drag an image (of any normal type jpg, gif, etc) from a web site and drop it onto the .Net form where it will be saved to file and displayed.  The user should alsobe able to browse to a file in Windows Explorer and drag an image file onto the form for similar results.

I would be happy for the user to have to drop the image onto a PictureBox or similar control.
0
Comment
Question by:canuckconsulting
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 11

Assisted Solution

by:Visio_Guy
Visio_Guy earned 200 total points
ID: 36548448
There's a nice article over on CodeProject. It's pretty old, but nicely written, and I believe it still applies to WinForms.

A Simple Drag And Drop How To Example
http://www.codeproject.com/KB/cs/dandtutorial.aspx
0
 
LVL 40
ID: 36549918
You cannot do that.

In your application, you can control the Drop.

But the Drag must be initiated in the application that provides the object. Think of the security issues otherwise.

Since you cannot drag images from most application, there is no way to drop them into yours.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 36550394
He wants to drag from a web site to his form:

    "This will allow the user to drag an image (of any normal type jpg, gif, etc) from a web site and drop it onto the .Net form"

The answer is, yes you can...but with stipulations.

Most other browsers support this out of the box but you have to parse the return value to get the URL and then actually download the image (it's really not that hard).

But Internet Explorer, the most common browser, will give you headaches on systems with Vista or higher because of UAC and the "Proctected Mode" in IE.  You have to turn off UAC or disable Protected Mode to be able to drag an image from a web page.   =\
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 300 total points
ID: 36550645
Here's an example...note in the screencast that I Right Click IE and select "Run as Administrator".  This is what necessary using RockMelt (browser based on Google Chrome):
Idle-Mind-500744.flv

Here's the code:
*The parsing code portion was written by Vaelek. I converted it from here:
http://codinghut.com/2007/11/capture-url-of-images-dropped-from-ie-to-your-form-control/
Imports System.IO
Imports System.Net
Imports System.Text.RegularExpressions
Public Class Form1

    Private URL_DataFormat As String = "HTML format"

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        PictureBox1.AllowDrop = True
    End Sub

    Private Sub PictureBox1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox1.DragEnter
        If e.Data.GetDataPresent(URL_DataFormat) Then
            e.Effect = DragDropEffects.Copy
        End If
    End Sub

    Private Sub PictureBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox1.DragDrop
        Dim clipboardHtml As String = e.Data.GetData("HTML Format").ToString
        Dim htmlFragment As String = getHtmlFragment(clipboardHtml)
        Dim imageSrc As String = parseImageSrc(htmlFragment)
        Dim baseURL As String = parseBaseURL(clipboardHtml)
        Dim ImageURL As String = ""
        If imageSrc.ToUpper().StartsWith("HTTP://") Then
            ImageURL = imageSrc
        Else
            ImageURL = baseURL + imageSrc.Substring(1)
        End If

        Dim bgw As New System.ComponentModel.BackgroundWorker
        AddHandler bgw.DoWork, AddressOf bgw_DoWork
        AddHandler bgw.RunWorkerCompleted, AddressOf bgw_RunWorkerCompleted
        Me.Text = "Downloading Image..."
        bgw.RunWorkerAsync(ImageURL)
    End Sub

    Public Function getHtmlFragment(ByVal clipboardHtml As String) As String
        Dim fragStartPos As Integer = Integer.Parse(Regex.Match(clipboardHtml, "StartFragment:(\d+)", RegexOptions.Multiline).Groups(1).Value)
        Dim fragEndPos As Integer = Integer.Parse(Regex.Match(clipboardHtml, "^EndFragment:(\d+)", RegexOptions.Multiline).Groups(1).Value)
        Return clipboardHtml.Substring(fragStartPos, fragEndPos - fragStartPos)
    End Function

    Public Function parseImageSrc(ByVal html As String) As String
        Return Regex.Match(html, "<img.*?src=[""'](.*?)[""'].*>", RegexOptions.IgnoreCase Or RegexOptions.Singleline).Groups(1).Value
    End Function

    Public Function parseBaseURL(ByVal html As String) As String
        Return Regex.Match(html, "http://.*?/", RegexOptions.IgnoreCase).Groups(0).Value
    End Function

    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Dim url As String = e.Argument
        Dim img As Image = GetWebImage(url)
        img.Tag = url
        e.Result = img
    End Sub

    Private Function GetWebImage(ByVal URL As String) As Image
        Try
            Dim wReq As WebRequest = WebRequest.Create(URL)
            If Not IsNothing(wReq) Then
                Dim wRes As WebResponse = wReq.GetResponse
                If Not IsNothing(wRes) Then
                    Dim wStrm As Stream = wRes.GetResponseStream
                    If Not IsNothing(wStrm) Then
                        Return Image.FromStream(wStrm)
                    End If
                End If
            End If
        Catch ex As Exception
        End Try
        Return Nothing
    End Function

    Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
        Dim img As Image = e.Result
        If Not IsNothing(img) Then
            Me.Text = img.Tag.ToString
            PictureBox1.Image = img

            ' if you want to save it:
            ' img.Save(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "SomeFile.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)
        Else
            Me.Text = "Oops!"
            MessageBox.Show("Failed to get image...")
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Text = "Form1"
        PictureBox1.Image = Nothing
    End Sub

End Class

Open in new window

0
 
LVL 40
ID: 36550649
He also wants to drag from the browser:

   "should alsobe able to browse to a file in Windows Explorer and drag an image file onto the form for similar results."

I think the expressiond web site and file are not used in the right context :-)

-------

There is an option to save the picture in a file in most browsers, usually on the context menu when you right click on an image. Do you really need an application to save the file for the user?

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 36550655
*The "what" below should read "not" !

    "This is what necessary using RockMelt (browser based on Google Chrome)"
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 36550665
Right...I believe he wants to both be able to drag and drop a local image from Windows Explorer and an image from a web page.

There are many examples on the net showing how to accomplish the local drag and drop from Windows Explorer.
0
 

Author Closing Comment

by:canuckconsulting
ID: 36945262
Thank you and I'm sorry for not following up on this earlier!  Yes, I wanted to do both things (drag a file from Windows Explorer and drag an image from a web browser).  These two answer have me on the right path!

The reason I want this is the images will be resized and thumbnails created from the resized image.  Both these images will then be submitted to a DB.
0

Featured Post

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Come and listen to Percona CEO Peter Zaitsev discuss what’s new in Percona open source software, including Percona Server for MySQL (https://www.percona.com/software/mysql-database/percona-server) and MongoDB (https://www.percona.com/software/mongo-…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question