我的应用程序接收来自Internet的拖放链接,并尝试从提供的链接创建图像。
代码看起来像这样。
if (link.StartsWith("http"))
{
try
{
itemImage.Source = new BitmapImage(new Uri(link));
if (itemImage.Source != null)
{
if (itemImage.Visibility == Visibility.Collapsed)
ShowImage();
}
}
catch (Exception){}
}
当提供的链接包含图像路径时,它可以很好地处理它的工作。 如果路径是例如“https://stackoverflow.com/”程序假定此链接也提供图像,那么它在if条件(imageSource!= null)内运行代码并显示空图像。
然而,当按下按钮以保存无效的“图像”并检查Source是否真的为null程序运行ShowNameError方法(假设名称设置正确)
if (itemImage.Source == null || name == string.Empty)
{
ShowNameError("Set name or/and image of item first");
return;
}
换句话说 - ImageSource在第一个条件下不为null,但在第二个条件下它是null,这没有意义,因为代码ImageSource中的任何地方都不再被操纵。
既然魔术技巧正在发生,我问你如何检查Uri IS创建的BitmapImage是否真的是一个图像?
答案 0 :(得分:0)
您可以使用魔术字节来查看'如果图像实际上是已知的图像格式。您可以在Wikipedia上看到完整列表。
例如,PNG始终以89 50 4E 47 0D 0A 1A 0A
开头。您可以下载二进制数据,并根据PNG,JPG,BMP等的魔术字节检查二进制结果。如果匹配,您可能会安全。
答案 1 :(得分:0)
您应该检查BitmapImage是否已立即加载位图。如果IsDownloading
属性为true,请附加DownloadCompleted
处理程序以及DownloadFailed
事件的处理程序:
var image = new BitmapImage(new Uri(link));
if (image.IsDownloading)
{
image.DownloadCompleted += (s, e) => ShowImage(image);
}
else
{
ShowImage(image);
}