确定复制到剪贴板中的文件是否为图像

用户右键单击文件(例如在桌面上)并单击“复制”。 现在如何在C#中确定复制到剪贴板的文件是否为图像类型?

Clipboard.ContainsImage()在这种情况下不起作用

以下确定是否将图像直接复制到剪贴板,而不是将文件复制到剪贴板

IDataObject d = Clipboard.GetDataObject(); if(d.GetDataPresent(DataFormats.Bitmap)) { MessageBox.Show("image file found"); } 

为了清楚起见,我想确定复制到剪贴板的“文件”是否是图像。

编辑:答案很棒,但如何将文件的文件名复制到剪贴板? Clipboard.getText()似乎不起作用.. Edit2:Clipboard.GetFileDropList()工作原理

您可以像这样检查它(没有内置的方法)读取文件并在图形图像对象中使用它,如果它将是图像它将工作正常,否则它将引发OutOfMemoryException

这是一个示例代码:

  bool IsAnImage(string filename) { try { Image newImage = Image.FromFile(filename); } catch (OutOfMemoryException ex) { // Image.FromFile will throw this if file is invalid. return false; } return true; } 

它适用于BMP,GIF,JPEG,PNG,TIFF文件格式


更新

以下是获取FileName的代码:

 IDataObject d = Clipboard.GetDataObject(); if(d.GetDataPresent(DataFormats.FileDrop)) { //This line gets all the file paths that were selected in explorer string[] files = d.GetData(DataFormats.FileDrop); //Get the name of the file. This line only gets the first file name if many file were selected in explorer string TheImageFile = files[0]; //Use above method to check if file is Image file if(IsAnImage(TheImageFile)) { //Process file if is an image } { //Process file if not an image } } 

从剪贴板中获取文件名(将文件复制到剪贴板只是复制其名称)。 然后检查文件是否是图像。

有两种方法可以做到这一点:

  1. 通过文件扩展名
  2. 打开文件并检查指示常见图像格式的魔术字节

我更喜欢第二个,因为它即使文件的扩展名错误也能正常工作。 在慢速媒体上,它可能会更慢,因为您需要访问文件而不是仅仅处理从剪贴板获取的文件名。

如果包含图像,您可以轻松检查剪贴板:

 if (Clipboard.ContainsImage()) { MessageBox.Show("Yes this is an image."); } else { MessageBox.Show("No this is not an image!"); }