moha
moha

Reputation: 23

Clipboard.SetImage doesn't work

I'm trying to download image from a URL and set it to the Clipboard (WPF). I can paste image to Paint but not to a local directory.

Here is my codes downloading and setting to clipboard:

var request = WebRequest.Create(urlImg); // urlImg  - url of image
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
var bitmap2 = new Bitmap(responseStream);

var orgimg = LoadBitmap2(bitmap2); // converting to BitmapSource
Clipboard.SetImage(orgimg);

Upvotes: 1

Views: 2503

Answers (1)

Kyle
Kyle

Reputation: 1365

When you cut/copy and paste an image to the file system only the path(s) are in the clipboard data.

If you want to 'paste' a downloaded image to a directory you'll need to emulate that behaviour:

  1. Write the downloaded image to a temp directory
  2. Set up the clipboard with the appropriate paste data (see DataFormats.FileDrop)
  3. Make sure the mode is set to 'cut' so that the image isn't left in the temp location

Example

string url = "http://example.com/images/someimage.jpeg";
var img = GetImageFromUrl(url);

//write the image to a temporary location (todo: purge it later)
var tmpFilePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(url));
img.Save(tmpFilePath);

//group image(s)
var imgCollection = new System.Collections.Specialized.StringCollection();
imgCollection.Add(tmpFilePath);

//changing the drop affect to 'move' from the temp location
byte[] moveEffect = new byte[] { 2, 0, 0, 0 };
MemoryStream dropEffect = new MemoryStream();
dropEffect.Write(moveEffect, 0, moveEffect.Length);

//set up our clipboard data
DataObject data = new DataObject();
data.SetFileDropList(imgCollection);
data.SetData("Preferred DropEffect", dropEffect);

//push it all to the clipboard
Clipboard.Clear();
Clipboard.SetDataObject(data, true);

Where GetImageFromUrl() is:

private System.Drawing.Image GetImageFromUrl(string url)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

    using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
    {
        using (Stream stream = httpWebReponse.GetResponseStream())
        {
            return System.Drawing.Image.FromStream(stream);
        }
    }
}

Note: You'll need to add a reference to System.Drawing for the Image class. I'm sure there's an alternative in the WPF spaces.

Further Reading

Upvotes: 2

Related Questions