40分!GDI+转换图形文件数据到StdPicture,如何释放Stream?
本帖最后由 liucqa 于 2013-04-15 21:14:28 编辑
Public Function body2Image(ByRef imgbody() As Byte) As StdPicture
Dim iWidth As Long '以像素为单位的图形宽度
Dim iHeight As Long '以像素为单位的图形高度
Dim lStream As Long
Dim hDC As Long, hDCmem As Long, lrtn As Long
Dim lBitmap As Long
Dim hBitmap As Long
Dim tPictDesc As PicBmp
Dim IID_IPicture As GUID
Dim oPicture As StdPicture
Call GDI_Initialize
'hDC = GetDC(0)
Call CreateStreamOnHGlobal(imgbody(0), False, lStream)
'从Stream加载Bitmap
If GdipLoadImageFromStream(lStream, lBitmap) = OK Then
'根据Bitmap创建hBitbmp
If GdipCreateHBITMAPFromBitmap(lBitmap, hBitmap, 0) = OK Then
With tPictDesc
.Size = Len(tPictDesc)
.Type = vbPicTypeBitmap
.hBmp = hBitmap
.hPal = 0
End With
' 初始化IPicture
With IID_IPicture
.Data1 = &H7BF80981
.Data2 = &HBF32
.Data3 = &H101A
.Data4(0) = &H8B
.Data4(1) = &HBB
.Data4(3) = &HAA
.Data4(5) = &H30
.Data4(6) = &HC
.Data4(7) = &HAB
End With
Call OleCreatePictureIndirect(tPictDesc, IID_IPicture, True, oPicture)
Set body2Image = oPicture
End If
End If
GdipDisposeImage lBitmap '释放lBitmap
'Call ReleaseDC(0, hDC)
Call GDI_Terminate
End Function
请问上面的代码中,lStream是否需要释放?如何释放呢?
这段代码是否还有内存泄漏问题?
[解决办法]
不用释放,销毁GDI+就OK了.
[解决办法]
接下来讲一个不使用类型库释放对象的小技巧:
'释放IStream对象
Private Function ReleaseStream(ByVal lpStream As Long) As Boolean
Dim lpThis As Long
Dim lpVTable As Long
Dim oTmp As Collection
If lpStream = 0 Then Exit Function
Set oTmp = New Collection
lpThis = ObjPtr(oTmp)
CopyMemory lpVTable, ByVal lpThis, 4
CopyMemory ByVal lpThis, ByVal lpStream, 4
Set oTmp = Nothing
CopyMemory ByVal lpThis, lpVTable, 4
Set oTmp = Nothing
ReleaseStream = True
End Function
以上复制自CSDN