我尝试在Microsoft Word中获取图片形状的文本。为此,我使用了Windows 10 windows.media.ocr
中包含的OCR库。由于OCREngine
需要SoftwareBitmap
我还没有合作过,但我尝试了以下方法来实现SoftwareBitmap
:
oWordDocument.Shapes(1).Select() '*** Get shape and copy to clipboard and then to bitmap
oWordApp.Selection.CopyAsPicture()
Dim oBitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(System.Windows.Forms.Clipboard.GetImage())
Dim oSoftwareBitmap As Windows.Graphics.Imaging.SoftwareBitmap
Dim oUWPStream As Windows.Storage.Streams.IRandomAccessStream
Using oNetStream As New System.IO.MemoryStream '*** Get UWP-Stream via .Net-Stream
oBitmap.Save(oNetStream, System.Drawing.Imaging.ImageFormat.Png)
oUWPStream = System.IO.WindowsRuntimeStreamExtensions.AsRandomAccessStream(oNetStream)
'*** in the following line an invalidcast error occurs "Unable to cast object of type 'System.__ComObject' to type 'Windows.Graphics.Imaging.BitmapDecoder'."
Dim oBitmapDecoder As Windows.Graphics.Imaging.BitmapDecoder = Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(Windows.Graphics.Imaging.BitmapDecoder.PngDecoderId, oUWPStream)
oSoftwareBitmap = oBitmapDecoder.GetSoftwareBitmapAsync()
End Using
所以现在代码运行正常,直到我尝试创建BitmapDecoder。从我所看到的,我提供了一个有效的RandomAccessStream,但创建失败,无效。
有人可以请求帮助,甚至提供或指向我创建BitmapDecoder和SoftwareBitmap的代码示例吗?
很抱歉,如果描述复杂或令人困惑 - 英语不是我的母语
问题解决了:实际上解决方案非常简单。我第一次没理解它。我从一开始就知道我应该使用等待异步方法,但我总是遇到来自可视化编辑器的非常有用的错误消息。这只是因为缺少异步上下文。在我的事件处理程序Private Async Sub SelectFilesButton_Click(sender As Object, e As EventArgs) Handles SelectFilesButton.Click
中添加了async关键字后,一切正常,我可以按预期使用await语句。
以下是与上述代码相对应的最终解决方案:
'*** Get Bitmap from Word Bitmap-Shape
oWordDocument.Shapes(1).Select()
oWordApp.Selection.CopyAsPicture()
Dim oBitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(System.Windows.Forms.Clipboard.GetImage())
'*** Convert Streams, get BitmapDecoder + SoftwareBitmap
Using oNetStream As New System.IO.MemoryStream
oBitmap.Save(oNetStream, System.Drawing.Imaging.ImageFormat.Png)
Dim oUWPStream As Windows.Storage.Streams.IRandomAccessStream = System.IO.WindowsRuntimeStreamExtensions.AsRandomAccessStream(oNetStream)
Dim oBitmapDecoder As Windows.Graphics.Imaging.BitmapDecoder = Await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(oUWPStream)
Dim oSoftwareBitmap As Windows.Graphics.Imaging.SoftwareBitmap = Await oBitmapDecoder.GetSoftwareBitmapAsync()
End Using
感谢Jimi指出我正确的方向 - 抱歉让我这么久才明白
PS:非常有帮助理解这是来自微软编程指南的2篇文章,您可以使用以下搜索术语找到它们: " 异步程序中的控制流程(Visual Basic)"和 " 使用异步和等待进行异步编程(Visual Basic)"