如何为 WPF VB.NET 将 Bitmap 转换为 BitmapImage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20027083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Bitmap to BitmapImage for WPF VB.NET
提问by MC9000
I'm trying to convert a Bitmap to a BitmapImage in WPF. Basically, I'm starting with a Bitmap created in memory (from another process) and I need to use it elsewhere, but as a BitmapImage.
我正在尝试在 WPF 中将 Bitmap 转换为 BitmapImage。基本上,我从在内存中创建的位图(来自另一个进程)开始,我需要在其他地方使用它,但作为 BitmapImage。
I found this answer question 6484357, but the author's function Bitmap2BitmapImage does not work (at least in DotNet4.5) as there is no such method called Imaging.CreateBitmapSourceFromHBitmap - so no luck there (at least no way to convert to a VB.Net equivalent function).
我找到了这个答案问题 6484357,但作者的函数 Bitmap2BitmapImage 不起作用(至少在 DotNet4.5 中),因为没有这样的方法叫做 Imaging.CreateBitmapSourceFromHBitmap - 所以没有运气(至少没有办法转换为 VB.Net等效功能)。
回答by Trae Moore
Incorporating question 6484357 and translated to vb.net
纳入问题 6484357 并翻译到 vb.net
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Windows
Imports System.Windows.Interop
Imports System.Windows.Media.Imaging
Namespace StackConsoleTesting
Class Program
Private Function BitmapImage2Bitmap(bitmapImage As BitmapImage) As Bitmap
BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));
Using outStream = New MemoryStream()
Dim enc As BitmapEncoder = New BmpBitmapEncoder()
enc.Frames.Add(BitmapFrame.Create(bitmapImage))
enc.Save(outStream)
Dim bitmap As New System.Drawing.Bitmap(outStream)
Return New Bitmap(bitmap)
End Using
End Function
<System.Runtime.InteropServices.DllImport("gdi32.dll")> _
Public Shared Function DeleteObject(hObject As IntPtr) As Boolean
End Function
Private Function Bitmap2BitmapImage(bitmap As Bitmap) As BitmapImage
Dim hBitmap As IntPtr = bitmap.GetHbitmap()
Dim retval As BitmapImage
Try
Dim bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())
Dim encoder = New BmpBitmapEncoder()
Dim memoryStream = New MemoryStream()
encoder.Frames.Add(BitmapFrame.Create(bitmapSource))
encoder.Save(memoryStream)
retval.BeginInit()
retval.StreamSource = New MemoryStream(memoryStream.ToArray())
retval.EndInit()
memoryStream.Close()
Return retval
End Function
End Class
End Namespace

