-->

ArgumentException not caught when using BitmapImag

2019-09-12 07:31发布

问题:

Why when an ArgumentException occurs because image.jpg has an invalid metadata header does the first example catch the exception, and the second example does not?

Example 1:

try
{
Uri myUri = new Uri("http://example.com/image.jpg", UriKind.RelativeOrAbsolute);
JpegBitmapDecoder decoder2 = new JpegBitmapDecoder(myUri,
                             BitmapCreateOptions.PreservePixelFormat,
                             BitmapCacheOption.Default);
BitmapSource bitmapSource2 = decoder2.Frames[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Example 2:

try
{
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri("http://example.com/image.jpg");
src.EndInit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

回答1:

It might be waiting until the image is requested to load it up, such as being set as the source for an Image control.

Perhaps it would give you an exception if you added

src.CacheOption = BitmapCacheOption.OnLoad;

to your declarations.