如何将Bitmap转换为WPF VB.NET的BitmapImage

时间:2013-11-17 04:10:02

标签: c# wpf vb.net bitmap bitmapimage

我正在尝试将位图转换为WPF中的BitmapImage。基本上,我开始在内存中创建一个Bitmap(来自另一个进程),我需要在别处使用它,但是作为BitmapImage。

我找到了这个答案question 6484357,但作者的函数Bitmap2BitmapImage不起作用(至少在DotNet4.5中),因为没有这样的方法叫做Imaging.CreateBitmapSourceFromHBitmap - 所以没有运气(至少没办法转换为VB.Net等效函数)。

1 个答案:

答案 0 :(得分:1)

合并问题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