如何检查 Uri 创建的 BitmapImage 是否真的是一个图像?

How to check if BitmapImage created by Uri is actually an image?

我的应用程序从 Internet 接收拖放 links 并尝试从提供的 link.

创建图像

代码如下所示。

if (link.StartsWith("http"))
{
    try
    {
        itemImage.Source = new BitmapImage(new Uri(link));
        if (itemImage.Source != null)
        {
            if (itemImage.Visibility == Visibility.Collapsed)
                ShowImage();
        }
    }
    catch (Exception){}
}

在提供 link 包含图像路径的那一刻,它可以很好地处理它的工作。 例如,如果路径是“https://whosebug.com/”,程序假定此 link 也提供图像,因此它是 if 条件 (imageSource != null) 内的 运行 代码并显示空图像。

然而,当按下按钮保存无效 "image" 并检查 Source 是否真的为 null 时,程序运行 ShowNameError 方法(假设名称设置正确)

if (itemImage.Source == null || name == string.Empty)
{
    ShowNameError("Set name or/and image of item first");
    return;
}

换句话说 - ImageSource 在第一个条件下不为空,但在第二个条件下它为空,这没有意义,因为代码中的任何地方都不再操纵 ImageSource。

由于魔术正在发生,我想问你如何检查 Uri 创建的 BitmapImage 是否真的是图像?

如果图像实际上是已知图像格式,您可以对 'see' 使用魔法字节。您可以在 Wikipedia.

上查看完整列表

例如,PNG 总是以 89 50 4E 47 0D 0A 1A 0A 开头。您可以下载二进制数据并根据 PNG、JPG、BMP 等的魔术字节检查二进制结果。如果匹配,您可能是安全的。

您应该检查BitmapImage 是否立即加载了位图。如果 IsDownloading 属性 为真,则为 DownloadCompleted 和可选的 DownloadFailed 事件附加处理程序:

var image = new BitmapImage(new Uri(link));

if (image.IsDownloading)
{
    image.DownloadCompleted += (s, e) => ShowImage(image);
}
else
{
    ShowImage(image);
}