Available in the LEADTOOLS Imaging toolkit. |
LoadMemory example for Visual Basic
This example uses WIN16 API calls to load a file into memory, then uses the LoadMemory method to load the memory-resident file into a bitmap.
' Declare WIN16 API constants and functions in the Declarations module.
Private Const OF_READ = &H0
Private Const OF_CREATE = &H1000
Private Const SEEK_SET = 0
Private Const SEEK_END = 2
Private Const GMEM_MOVEABLE = &H2
Private Type OFSTRUCT
cBytes As String * 1
fFixedDisk As String * 1
nErrCode As Integer
reserved As String * 4
szPathName As String * 128
End Type
Private Declare Function OpenFile Lib "kernel" (ByVal lpFileName As String, lpReOpenBuff As OFSTRUCT, ByVal wStyle As Integer) As Integer
Private Declare Function hread Lib "kernel" Alias "_hread" (ByVal hFile As Integer, ByVal lpBuffer As Long, ByVal wBytes As Long) As Long
Private Declare Function hwrite Lib "kernel" Alias "_hwrite" (ByVal hFile As Integer, ByVal lpBuffer As Long, ByVal lBytes As Long) As Long
Private Declare Function lclose Lib "kernel" Alias "_lclose" (ByVal hFile As Integer) As Integer
Private Declare Function llseek Lib "kernel" Alias "_llseek"(ByVal hFile As Integer, ByVal lOffset As Long, ByVal iOrigin As Integer) As Long
Private Declare Function GlobalAlloc Lib "kernel" (ByVal wFlags As Integer, ByVal dwBytes As Long) As Integer
Private Declare Function GlobalFree Lib "kernel" (ByVal hMem As Integer) As Integer
Private Declare Function GlobalLock Lib "kernel" (ByVal hMem As Integer) As Long
Private Declare Function GlobalUnlock Lib "kernel" (ByVal hMem As Integer) As Integer
' ---------------------- Code for LoadMemory (16 bit) -------------
Private Sub LoadMemory_Click()
Dim hf As Integer ' For WIN32 declare this as Long
Dim hMem As Integer ' For WIN32 declare this as Long
Dim lpMem As Long
Dim iSize As Long
Dim of As OFSTRUCT
Dim nRet As Long
' Load the file into memory.
hf = OpenFile("c:\lead\images\image1.cmp", of, OF_READ)
If hf = -1 Then
MsgBox ("Error opening file!")
GoTo quit_loadmemory
End If
iSize = llseek(hf, 0, SEEK_END)
nRet = llseek(hf, 0, SEEK_SET)
hMem = GlobalAlloc(GMEM_MOVEABLE, iSize)
If hMem = -1 Then
lclose (hf)
MsgBox ("Not enough memory to hold the file in memory!")
GoTo quit_loadmemory
End If
lpMem = GlobalLock(hMem)
If lpMem = 0 Then
lclose (hf)
GlobalFree (hMem)
MsgBox ("Not enough memory to hold the file in memory!")
GoTo quit_loadmemory
End If
If hread(hf, lpMem, iSize) < iSize Then
lclose (hf)
GlobalUnlock (hMem)
GlobalFree (hMem)
MsgBox ("Error reading file")
GoTo quit_loadmemory
End If
lclose (hf)
GlobalUnlock (hMem)
'Load the bitmap from the memory-resident file.
If Lead1.LoadMemory(hMem, 0, 0, -1, iSize) <> 0 Then
MsgBox ("Error calling LoadMemory")
Else
MsgBox ("LoadMemory succeeded")
End If
GlobalFree (hMem)
quit_loadmemory:
End Sub