Solved

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

Posted on 2011-09-16
8
253 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
8 Comments
 
LVL 11

Assisted Solution

by:Visio_Guy
Visio_Guy earned 200 total points
Comment Utility
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

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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 85

Expert Comment

by:Mike Tomlinson
Comment Utility
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
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 300 total points
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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 85

Expert Comment

by:Mike Tomlinson
Comment Utility
*The "what" below should read "not" !

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

Expert Comment

by:Mike Tomlinson
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Visual Studio installation 5 32
Problem to Popup 2 48
Problem to go to Web page 2 46
Loop through Multiple Processes Async 2 15
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This video discusses moving either the default database or any database to a new volume.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now