2008-11-07 VB.Net 如何將 Image 與 StdPicture 做轉換 10712 0 VB / VBA 摘要:VB.Net 如何將 Image 與 StdPicture 做轉換 VB.Net 如何互轉 System.Drawing.Image 與 OLE StdPicture 方法 1 : Call OleCreatePictureIndirect API Imports System.Drawing Imports System.Runtime.InteropServices Public Class Form1 ' 宣告引用 API <DllImport("OLEPRO32.DLL", PreserveSig:=False)> _ Private Shared Function OleCreatePictureIndirect _ (ByRef pPictDesc As PicDesc, ByRef riid As Guid, ByVal fOwn As Boolean) As _ <MarshalAs(UnmanagedType.IUnknown)> Object End Function ' 宣告結構 Private Structure PicDesc Friend SizeOfStruct As Integer Friend PicType As Integer Friend Hbitmap As IntPtr Friend Hpal As IntPtr Friend Padding As Integer Friend Sub New(ByVal hBmp As IntPtr) Hbitmap = hBmp SizeOfStruct = Marshal.SizeOf(Me.GetType) PicType = 1 Hpal = IntPtr.Zero Padding = 0 End Sub End Structure ' 取得 StdPicture Private Function GetStdPic(ByRef img As Image) _ As <MarshalAs(UnmanagedType.IUnknown)> Object ' 呼叫 API OleCreatePictureIndirect 轉 IPicture Return OleCreatePictureIndirect( _ New PicDesc(New Bitmap(img).GetHbitmap), _ New Guid("{7BF80980-BF32-101A-8BBB-00AA00300CAB}"), True) End Function Private Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click Dim img As Image = Image.FromFile("C:\Genius.jpg") ' 讀入 JPG 圖檔 PictureBox1.Image = img MessageBox.Show(img.GetType.ToString) Dim pic As Object = GetStdPic(img) ' StdPicture MessageBox.Show(TypeName(pic) & " (" & pic.GetType.ToString & ")") End Sub方法 2 : 引用 Microsoft.VisualBasic.Compatibility請先加入參考 Microsoft.VisualBasic.CompatibilityImports Microsoft.VisualBasic.Compatibility Public Class Form1 Private Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click Dim img As Image = Image.FromFile("C:\Genius.jpg") ' 讀 JPG 圖檔進 Image 物件 MessageBox.Show(img.GetType.ToString) ' 將 Image 物件 轉 OLE IPicture 物件 Dim pic As Object = VB6.ImageToIPicture(img) ' StdPicture MessageBox.Show(TypeName(pic) & " (" & pic.GetType.ToString & ")") ' 將 OLE IPicture 物件 轉 Image 物件 PictureBox1.Image = VB6.IPictureToImage(pic) End Sub End Class 回首頁