简体   繁体   English

Clipboard.SetImage不起作用

[英]Clipboard.SetImage doesn't work

I'm trying to download image from a URL and set it to the Clipboard (WPF). 我正在尝试从URL下载图像并将其设置为剪贴板(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);

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 ) 使用适当的粘贴数据设置剪贴板(请参见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: 其中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);
        }
    }
}

Note: You'll need to add a reference to System.Drawing for the Image class. 注意:您需要为Image类添加对System.Drawing的引用。 I'm sure there's an alternative in the WPF spaces. 我确定WPF空间中还有其他选择。

Further Reading 进一步阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM