Determine if file copied into clipboard is an image

后端 未结 3 1930
时光说笑
时光说笑 2021-01-05 08:58

The user right clicks on a file(say on the desktop) and clicks \'copy\' . Now how do I determine in C# if the file copied to the clipboard is an image type ?

Clipbo

3条回答
  •  长发绾君心
    2021-01-05 09:22

    You can check it like this (There is no built in way of doing this) Read the file and use it in a Graphics Image Object if it will be image it will work fine else it will Raise an OutOfMemoryException.

    here is a sample code:

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

    It will work for BMP, GIF, JPEG, PNG, TIFF file formats


    Update

    Here is the code to get the 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
        }
    }
    

提交回复
热议问题