How to catch this Bitmap WPF download exception?

I am developing an application that downloads bitmaps from the Internet using .NET 3.5 sp1 and C #.

The download code looks like this:

try { CurrentImage = pics[unChosenPics[index]]; bi = new BitmapImage(CurrentImage.URI); // BitmapImage.UriSource must be in a BeginInit/EndInit block. bi.DownloadCompleted += new EventHandler(bi_DownloadCompleted); AssessmentImage.Source = bi; } catch { System.Console.WriteLine("Something broke during the read!"); } 

and bi_DownloadCompleted download code:

  void bi_DownloadCompleted(object sender, EventArgs e) { try { double dpi = 96; int width = bi.PixelWidth; int height = bi.PixelHeight; int stride = width * 4; // 4 bytes per pixel byte[] pixelData = new byte[stride * height]; bi.CopyPixels(pixelData, stride, 0); BitmapSource bmpSource = BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgra32, null, pixelData, stride); AssessmentImage.Source = bmpSource; Loading.Visibility = Visibility.Hidden; AssessmentImage.Visibility = Visibility.Visible; } catch { System.Console.WriteLine("Exception when viewing bitmap."); } } 

Each so often appears image that breaks the reader. I think this should be expected. However, instead of being caught by one of these try / catch blocks, the exception obviously throws itself beyond where I can handle it. I could handle this using WPF global exceptions such as this SO question . However, this will seriously ruin the control flow of my program, and I would like to avoid it, if at all possible.

I need to perform a dual-source assignment, because it seems that many images do not have width and height parameters in the places where the microsoft bitmap loader expects them. Thus, the first assignment forces the download to load, and the second assignment gets the dpi / image size.

What can I do to catch and handle this exception?

If you want to replicate, try downloading this image as uri:

 http://i.pbase.com/o2/26/519326/1/123513540.Yub8hciV.Longford12.jpg 

The exception itself:

 System.ArgumentException in PresentationCore Value does not fall within the expected range. 

Internal exception:

 An invalid character was found in text context. 

Stack trace:

  at MS.Internal.HRESULT.Check(Int32 hr) at System.Windows.Media.Imaging.BitmapFrameDecode.get_ColorContexts() at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation() at System.Windows.Media.Imaging.BitmapImage.OnDownloadCompleted(Object sender, EventArgs e) at System.Windows.Media.UniqueEventHelper.InvokeEvents(Object sender, EventArgs args) at System.Windows.Media.Imaging.LateBoundBitmapDecoder.DownloadCallback(Object arg) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Application.RunInternal(Window window) at LensComparison.App.Main() in C:\Users\Mark64\Documents\Visual Studio 2008\Projects\LensComparison\LensComparison\obj\Release\App.g.cs:line 48 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() 
+4
source share
2 answers

This exception is the result of โ€œbrokenโ€ color profile information contained in the image. If you do not care about this information (or want to try to parse again after an exception), use the BitmapCreateOptions.IgnoreColorProfile flag.

Example:

 BitmapImage i = new BitmapImage(); i.BeginInit(); i.CreateOptions |= BitmapCreateOptions.IgnoreColorProfile; i.UriSource = new Uri(@"http://www.bing.com/fd/hpk2/KiteFestival_EN-US2111991920.jpg"); i.EndInit(); 

If you are looking for more information, check out Scott Hanselman . (We all talked about this issue today via email.)

+13
source

It works:

 try { frame = BitmapFrame.Create(new Uri("http://i.pbase.com/o2/26/519326/1/123513540.Yub8hciV.Longford12.jpg")); } catch { return; } 

There is a DecodeFailed event in BitmapFrame, but I canโ€™t connect it because BitmapFrame is frozen after it was created.

0
source

Source: https://habr.com/ru/post/1308274/


All Articles