我一直在开发一个图书浏览网站,它拍摄相当大的图像(大于 77 兆像素)并在提供图像之前将它们缩小。它基本上执行以下算法:
这是将单个图像减半的代码。注意BitmapImage的使用:
Private Shared Function HalveImage(ByVal baseImagePath As String, ByVal baseWidth As Integer, ByVal baseHeight As Integer, ByVal newImagePath As String) As BitmapImage
Dim bi As New BitmapImage
With bi
.BeginInit()
.UriSource = New Uri(baseImagePath)
.DecodePixelWidth = baseWidth / 2 'only seting one DecodePixelXXX property preserves the aspect ratio
.EndInit()
End With
Dim enc As New System.Windows.Media.Imaging.JpegBitmapEncoder
With enc
.QualityLevel = 50
.Frames.Add(BitmapFrame.Create(bi))
End With
Using stream As New IO.FileStream(newImagePath, IO.FileMode.Create)
enc.Save(stream)
End Using
Return bi
End Function
这段代码在我的开发机器上运行良好,但是当我将它安装到服务器上时,该服务器会在缓存数百张图像后突然停止缓存图像。网站的其余部分继续正常工作。我们发现页面缓存代码在每次尝试创建 BitmapImage 对象时最终都会抛出这个异常:
System.ComponentModel.Win32Exception: The system cannot find the file specified
at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D wc_d)
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at MS.Win32.MessageOnlyHwndWrapper..ctor()
at System.Windows.Threading.Dispatcher..ctor()
at System.Windows.Threading.Dispatcher.get_CurrentDispatcher()
at System.Windows.Freezable..ctor()
at System.Windows.Media.Imaging.BitmapSource..ctor(Boolean useVirtuals)
at System.Windows.Media.Imaging.BitmapImage..ctor()
at RemoteFSTester.PageCachingThreadPool.WICResizer.CachePage(String id, Int32 item, Int32 index) in C:\Users\[...]\PageCachingThreadPool.vb:line 127
at RemoteFSTester.PageCachingThreadPool.CachePage(String id, Int32 item, Int32 index) in C:\Users\[...]\PageCachingThreadPool.vb:line 103
at RemoteFSTester.PageCachingThreadPool.WorkerMethod(PriorityThreadPoolDelegateArgs args) in C:\Users\[...]\PageCachingThreadPool.vb:line 91
at MDSA.Util.PriorityThreadpool.PriorityThreadPoolBase.Thread_DoWork(PriorityThreadPoolDelegateArgs args) in C:\Users\[...]\PriorityThreadPoolBase.vb:line 199
即使异常显示“找不到指定的文件”,我也可以直接转到基本图像所在的位置并自己打开文件。
注意:澄清一下,存放代码和缓存图像的服务器不是存放基本图像的服务器。代码服务器通过像 '\servername\path\filename.jpg"这样的 URI 从基本图像服务器获取文件。
运行一些测试后,只有在尝试通过 BitmapImage 对象在我们的 IIS 服务器上打开图像时才会发生异常。无论我是通过 UriSource 设置文件路径还是创建 FileStream 对象并将 BitmapImage 的 StreamSource 属性设置为它,BitmapImage 中的异常都会发生。如果文件是通过 FileStream 对象打开的,它们不会发生,如果文件是通过控制台应用程序打开的,它们也不会发生。使用 BitmapImage 对象的控制台应用程序也可以正常运行。
所以,最后问我的问题,为什么服务器在我的开发机器没有问题的情况下通过 ASP.NET 缓存这些图像有问题?
最佳答案
我在这里找到了问题的解决方案:
Microsoft Connect Feedback
长话短说,我必须添加以下代码,它将在每个线程进程结束时运行:
Dim myDispatcher As Dispatcher = Dispatcher.CurrentDispatcher
myDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal)
Dispatcher.Run()
关于ASP.NET 在创建 BitmapImage 时抛出 Win32Exception,找不到指定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8995588/