Clipboard.SetImage不起作用

时间:2014-08-26 11:10:40

标签: c# wpf clipboard

我尝试从网址下载图片并将其设置为剪贴板(WPF)。我可以将图像粘贴到Paint但不粘贴到本地目录。

以下是我的代码下载和设置到剪贴板:

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);

1 个答案:

答案 0 :(得分:2)

当您将图像剪切/复制并粘贴到文件系统时,只有剪贴板数据中的路径。

如果您想将下载的图像“粘贴”到目录中,则需要模拟该行为:

  1. 将下载的图像写入临时目录
  2. 使用相应的粘贴数据设置剪贴板(请参阅DataFormats.FileDrop
  3. 确保将模式设置为“剪切”,以使图像不会留在临时位置
  4. 实施例

    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);
    

    GetImageFromUrl()的位置:

    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);
            }
        }
    }
    

    注意:您需要为System.Drawing课程添加Image的引用。我确信在WPF空间中有另一种选择。

    进一步阅读