Available in the LEADTOOLS Imaging toolkit. |
SaveMemory example for Visual J++
This example uses SaveMemory to save a bitmap to a memory-resident file, uses GetMemoryInfo to examine the file size; then uses WIN16 API calls to save the file to disk and free the memory.
// Declare WIN32 API constants and functions in the private section of your main form:
private final int OF_READ = 0x0;
private final int OF_CREATE = 0x1000;
private final int SEEK_SET = 0;
private final int SEEK_END = 2;
private final int GMEM_MOVEABLE = 0x2;
/** @dll.struct() */
class OFSTRUCT
{
byte cBytes;
byte fFixedDisk;
short nErrCode;
short Reserved1;
short Reserved2;
/** @dll.structmap([type=TCHAR[128]]) */
String szPathName;
}
static /** @dll.import("KERNEL32") */
class KernelAPIs
{
public static native int OpenFile( String lpFileName, OFSTRUCT lpReOpenBuff, int wStyle );
public static native int _hread( int hFile, int lpBuffer, int wBytes );
public static native int _hwrite( int hFile, int lpBuffer, int lBytes );
public static native int _lclose( int hFile );
public static native int _llseek( int hFile, int lOffset, int iOrigin );
public static native int GlobalAlloc( int wFlags, int dwBytes );
public static native int GlobalFree( int hMem );
public static native int GlobalLock ( int hMem );
public static native int GlobalUnlock ( int hMem );
}
private void button1_click(Object source, Event e)
{
int phMem[] = { 0 } ;
int piSize[] = { 0 } ;
if( LEAD1.SaveMemory( phMem, (short) LTOCXU.FileConstants.FILE_LEAD, (short) 24, (short) 2, piSize ) != 0 )
{
MessageBox.show( "Error calling SaveMemory" );
return;
}
int hMem = phMem[ 0 ];
int iSize = piSize[ 0 ];
if( LEAD1.GetMemoryInfo( hMem, (short) 0, iSize, 0 ) != 0 )
{
KernelAPIs.GlobalFree( hMem );
return;
}
// Ask for a confirmation to save this file
String strMsg = "File info:\n";
strMsg += LEAD1.getInfoWidth() + " x " + LEAD1.getInfoHeight();
strMsg += " x " + LEAD1.getInfoBits() + " BPP\n";
strMsg += "Size in memory: " + LEAD1.getInfoSizeMem() + "\n";
strMsg += "Size on disk : " + LEAD1.getInfoSizeDisk();
if( MessageBox.show( strMsg, "Write this file on disk", MessageBox.YESNO ) == MessageBox.IDNO )
{
KernelAPIs.GlobalFree( hMem );
return;
}
int lpMem = KernelAPIs.GlobalLock( hMem );
if( lpMem == 0 )
{
KernelAPIs.GlobalFree( hMem );
MessageBox.show( "Error calling GlobalLock" );
return;
}
OFSTRUCT of = new OFSTRUCT();
int hf = KernelAPIs.OpenFile( "c:\\lead\\images\\savemem.cmp", of, OF_CREATE );
if( hf == -1 )
{
KernelAPIs.GlobalUnlock( hMem );
KernelAPIs.GlobalFree( hMem );
MessageBox.show( "Error calling GlobalLock" );
return;
}
if( KernelAPIs._hwrite( hf, lpMem, iSize ) != iSize )
MessageBox.show( "Error calling hwrite" );
else
MessageBox.show( "The file was saved successfully on disk." );
KernelAPIs._lclose( hf );
KernelAPIs.GlobalUnlock( hMem );
KernelAPIs.GlobalFree( hMem );
}