我正在尝试处理我正在寻找的图像不存在的情况 - 它应该默认为股票图标图像。
即: - 当sampleimage = http://www.google.com/images/logos/ps_logo2.png时(存在 - 它应该返回正常) - 当sampleimage = http://www.thisimagedoesnotexist.com/something.png时(不存在 - 它应该进入catch块)
下面是我正在使用的代码 - 但是当图像不存在时永远不会进入catch块。我在Silverlight应用程序中使用它。关于如何让它发挥作用的任何消息?
try
{
image.Source = new BitmapImage(new Uri(sampleimage, UriKind.Absolute));
}
catch (OutOfMemoryException)
{
sampleimage = "defaulticon.jpg";
image.Source = new BitmapImage(new Uri(sampleimage, UriKind.Absolute));
}
答案 0 :(得分:3)
尝试以下代码
处理未找到网址的代码
Image image = new Image();
string sampleimage = "http://www.google.com/images/logos/ps_logo2.png";
Uri address;
if (TryGetUriAddress(out address, sampleimage))
{
image.Source = new BitmapImage(address);
}
else
{
sampleimage = "defaulticon.jpg";
image.Source = new BitmapImage(new Uri(sampleimage, UriKind.Absolute));
}
private bool TryGetUriAddress(out Uri validAddress,string addressToCreate)
{
bool isValid = false;
validAddress = null;
try
{
WebClient sc = new WebClient();
sc.DownloadData(addressToCreate);
validAddress = new Uri(addressToCreate, UriKind.Absolute);
isValid = true;
}
catch (Exception ex)
{
isValid = false;
}
return isValid;
}
答案 1 :(得分:1)
我希望Saurabh的解决方案能够奏效。我只是建议你的方法的替代方案。 在创建BitmapImage之前,尝试获取有效的URI,然后将其传递给BitmapImage构造函数。
Uri sampleURI;
try{
sampleURI = new Uri(sampleUriPath,UriKind.Absolute);
}catch(UriFormatException ufex)
{
sampleURI = new Uri(defaultUriPath,UriKind.Absolute);
}
image.Source = new BitmapImage(sampleURI);
答案 2 :(得分:1)
处理此问题的正确方法是使用ImageFailed
事件: -
bool defaultAssigned = false;
Image image = new Image();
image.ImageFailed += (s, args) =>
{
if (!defaultAssigned)
{
image.Source = new BitmapImage(defaultImageUri);
bDefaultAssigned = true;
}
}
image.Source = new BitmapImage(sampleImageUri);