2011-01-23 47 views
6

用戶右鍵單擊文件(例如在桌面上)並單擊「複製」。現在如何在C#中確定複製到剪貼板的文件是否爲圖像類型?確定複製到剪貼板的文件是否爲圖像

Clipboard.ContainsImage()在這種情況下不工作

以下確定某個圖像被直接複製到剪貼板,而不是如果一個文件被複制到剪貼板

IDataObject d = Clipboard.GetDataObject(); 

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

要清楚我想確定'文件'是否複製到剪貼板是一個圖像。

編輯:答案很好,但是如何獲取複製到剪貼板的文件的文件名? Clipboard.getText()似乎不工作..編輯2:Clipboard.GetFileDropList()的作品

+1

在許多情況下,檢查文件擴展名就足夠了。但是你可以使用`Magic-Bytes`方法(如CodeInChaos所說的)和``Exception Handling``方法(就像Shekhar_Pro所說的那樣)。還有一個名爲`TrID`的工具,它是一個免費的命令行實用程序,可用於使用簽名數據庫確定文件類型。 http://mark0.net/soft-trid-e.html – fardjad 2011-01-23 16:42:32

回答

6

你可以這樣檢查(沒有內置的方法) 讀取文件並在圖形圖像對象中使用它,如果它將是圖像,它將正常工作,否則將提高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文件格式


更新

在這裏工作是代碼來獲取文件名:

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 
    } 
} 
+0

這工作正常,除了我無法獲得複製到剪貼板的文件的文件名。任何想法如何獲得? – 2011-01-23 17:08:45

3

從剪貼板獲取文件名(複製文件到剪貼板只是複製其名稱)。然後檢查文件是否爲圖像。

有兩種方法做到這一點:

  1. 按文件擴展
  2. 打開該文件,並檢查魔法字節表示常見的圖像格式

我更喜歡第二個,因爲即使文件擴展名錯誤,它也能正常工作。在慢速媒體上,它可能會比較慢,因爲您需要訪問該文件,而不是隻處理從剪貼板獲得的文件名。

+0

感謝您指引我在正確的方向。通過文件擴展名似乎在這裏工作。我將不得不找出魔法字節的東西。 – 2011-01-23 16:35:17

0

您可以輕鬆檢查剪貼板是否包含圖像e是否:

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