如何抓住这个WPF位图加载异常? [英] How do I catch this WPF Bitmap loading exception?

查看:159
本文介绍了如何抓住这个WPF位图加载异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在开发一个使用.NET 3.5 sp1和C#加载位图的应用程序。加载代码如下所示:

  try {
CurrentImage = pics [unChosenPics [index]];
bi = new BitmapImage(CurrentImage.URI);
// BitmapImage.UriSource必须在BeginInit / EndInit块中。
bi.DownloadCompleted + = new EventHandler(bi_DownloadCompleted);
AssessmentImage.Source = bi;
}
catch {
System.Console.WriteLine(在读取期间发生了某些事情!);
}

并且bi_DownloadCompleted上加载的代码是:

  void bi_DownloadCompleted(object sender,EventArgs e){
try {
double dpi = 96;
int width = bi.PixelWidth;
int height = bi.PixelHeight;

int stride = width * 4; //每像素4字节
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(查看位图时的异常);
}
}

每隔一段时间,读者。我想这是可以预料的。但是,除了被这些try / catch块中的任何一个抓住,这个异常显然被抛出了我可以处理它的地方之外。我可以使用全局WPF异常来处理它,例如这个SO问题。但是,这将严重影响我的程序的控制流程,如果可能,我想避免这种情况。



我必须做双重源分配因为在微软位图加载器希望它们的位置看来,许多图像缺少宽/高参数。所以,第一个作业似乎强制下载,第二个任务会使dpi /图像尺寸发生正确。



我可以如何处理这个异常?



如果您想复制,请尝试将此图像作为uri加载:

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

异常本身是:

  PresentationCore中的System.ArgumentException 
值不落在预期范围内。

内部异常是:

 在文本上下文中找到一个无效的字符。 

堆栈跟踪:

 MS.Internal.HRESULT.Check(Int32小时)
在System.Windows.Media.Imaging.BitmapFrameDecode.get_ColorContexts()
在System.Windows.Media.Imaging.BitmapImage System.Windows.Media.Imaging.BitmapImage.OnDownloadCompletedFileizeCreation()
(Object sender,EventArgs e)
在System.Windows.Media.UniqueEventHelper.InvokeEvents(Object sender,EventArgs args)
在System.Windows.Media.Imaging.LateBoundBitmapDecoder.DownloadCallback(Object arg)
在System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调,Object args,Boolean isSingleParameter)
在System.Windows .Threading.ExceptionWrapper.TryCatchWhen(Object source,Delegate callback,Object args,Boolean isSingleParameter,Delegate catchHandler)
在System.Windows.Threading.DispatcherOperation.InvokeImpl()
在System.Threading.ExecutionContext.runTryCode (Object userData)
在Syst em.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode代码,CleanupCode backoutCode,Object userData)
在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)
在System.Windows。 Threading.DispatcherOperation.Invoke()
在System.Windows.Threading.Dispatcher.ProcessQueue()
在System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,布尔和放大器;处理)
在MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&被处理)
在MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
在System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback,Object args,Boolean isSingleParameter)
在System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,Delegate callback,Object args,Boolean isSingleParameter,Delegate catchHandler )
在System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority,TimeSpan timeout,Delegate方法,Object args,Boolean isSingleParameter)
在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32 msg, IntPtr wParam,IntPtr lParam)
在MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
在System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg)
在System.Windows .Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
在System.Windows.Application.RunInternal(窗口窗口)
在LensComparison.App.Main()在C:\Users\Mark64\Documents\Visual Studio 2008\Projects\LensComparison\LensComparison \obj\Release\App.g.cs:line 48
在System.AppDomain._nExecuteAssembly(Assembly assembly,String [] args)
在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly( )
在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state)
在System.Threading.ThreadHelper.ThreadStart()


解决方案

此异常是图像中包含的断开颜色配置文件信息的结果。如果你不关心这个信息(或者想尝试再次尝试解析之后),请使用BitmapCreateOptions.IgnoreColorProfile标志。



示例:

  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();

如果您正在寻找更多信息,请查看 Scott Hanselman的帖子。 (今天我们都通过电子邮件通信了这个问题。)


I'm developing an application that loads bitmaps off of the web using .NET 3.5 sp1 and C#.

The loading code looks like:

        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 the code to load on bi_DownloadCompleted is:

    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.");
        }
    }

Every so often, an image comes along that breaks the reader. I guess that's to be expected. However, rather than being caught by either of those try/catch blocks, the exception is apparently getting thrown outside of where I can handle it. I could handle it using global WPF exceptions, like this SO question. However, that will seriously mess up the control flow of my program, and I'd like to avoid that if at all possible.

I have to do the double source assignment because it appears that many images are lacking in width/height parameters in the places where the microsoft bitmap loader expects them to be. So, the first assignment appears to force the download, and the second assignment gets the dpi/image dimensions happen properly.

What can I do to catch and handle this exception?

If you'd like to replicate, try loading this image as the uri:

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

The exception itself is:

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

The inner exception is:

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()

解决方案

This exception is the result of 'broken' color profile information contained in the image. If you don't care about this information (or would like to try parsing again after 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're looking for more information, check out Scott Hanselman's post. (We were all in communication about this issue today, via email.)

这篇关于如何抓住这个WPF位图加载异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆