65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET WPF 图像处理程序

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.25/5 (4投票s)

2008年6月5日

CPOL

2分钟阅读

viewsIcon

40849

downloadIcon

431

一个 ASP.NET 处理程序,用于将 WPF XAML 模板应用于图像。

引言

本文档解释了如何使用 ASP.NET 处理程序来提供图像,使用 WPF 和 XAML 模板来操作图像。 效果令人惊叹,与任何商业组件都无法相提并论。

请记住:XAML 页面的根元素**必须**是“Page”。

背景

WPF 在 STA 线程中工作,ASP.NET 在 MTA 线程中工作,这是一个限制。

使用代码

该处理程序在 IIS 6 上工作。 在 IIS 7 上,我在渲染 3D 对象时遇到了一些问题(我正在解决)。

要使用该处理程序,需要调用“Xaml.ashx”,并传递一些必需的参数

  • w:宽度
  • h:高度
  • xaml:XAML 文件名(不带扩展名)
  • enc:编码器;可用选项:PNG、JPG、TIF、BMP、WMP、GIF

例如 URL:“xaml.ashx?w=500&h=300&xaml=xamlshield&enc=png”。

通过修改处理程序,还可以通过 URL 传递图像名称(查看注释代码)。

工作原理

处理程序有三个阶段

  1. 设置线程并启动它。
  2. 使用 XAML 读取器加载 XAML 文件。
  3. 捕获渲染输出,编码并发送它。

第一阶段在子程序 StartThread()

Dim thread As System.Threading.Thread = _
  New System.Threading.Thread(_
  New System.Threading.ThreadStart(AddressOf GimmeMore))
thread.SetApartmentState(System.Threading.ApartmentState.STA)
thread.IsBackground = True
thread.Start()
thread.Join()

我将线程的 ApartmentState 设置为 STA 并启动它。

第二阶段在子程序 GimmeMore()

Dim sr As New System.IO.StreamReader(_
  CurrentContext.Request.PhysicalApplicationPath + XamlDoc + ".xaml")
Dim xaml As String = sr.ReadToEnd()
sr.Close()
Dim ms As New System.IO.MemoryStream(xaml.Length)
Dim sw As New System.IO.StreamWriter(ms)
sw.Write(xaml)
sw.Flush()
ms.Seek(0, System.IO.SeekOrigin.Begin)
Dim parserContext As New ParserContext()
parserContext.BaseUri = New Uri(CurrentContext.Request.PhysicalApplicationPath)
MyImage = CType(System.Windows.Markup.XamlReader.Load(ms, parserContext), _
                System.Windows.Controls.Page)
'Dim ib As ImageBrush = MyImage.FindName("img")
'ib.ImageSource = New BitmapImage(New Uri(_
  CurrentContext.Request.PhysicalApplicationPath + "sunset.jpg"))
ms.Dispose()
Dim slt As PageDelegate
slt = New PageDelegate(AddressOf Capture)
MyImage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, _
                          slt, MyImage)

我加载 XAML 文件,并使用 Dispatcher.Invoke 调用捕获子程序。

注意:我注释了一些代码,您可以使用它来动态地将图像分配给 XAML 文件(在示例中,使用文件 xamlshield.xaml)。

在最后阶段(子程序 Capture()),我使用首选编码器捕获渲染输出。

注释

我为什么使用 Dispatcher.Invoke? 这是捕获渲染 XAML 中绑定的唯一经过测试的方法。

在 IIS 7 上,该处理程序工作,但**仅** Viewport3D 未渲染(没有 3D 效果)。 正在寻找解决方案....

历史和鸣谢

  • Marco Zhou,MSFT 和 MSDN 论坛版主。
  • Cristian Civera,MVP。
© . All rights reserved.