gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:11:42 25 4
gpt4 key购买 nike

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

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

下面判断是不是直接复制图片到剪贴板,不是复制文件到剪贴板

   IDataObject d = Clipboard.GetDataObject();

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

明确地说,我想确定复制到剪贴板的"file"是否是图像。

编辑:答案很好,但是如何获取复制到剪贴板的文件的文件名? 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 文件格式


更新

获取文件名的代码如下:

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

关于c# - 确定复制到剪贴板的文件是否为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com