|
Loading a .BMP file from file and displaying it in Delphi |
Step 1: Loading function
function LoadBitmapFile(FileName: String): HBitmap; var F: Integer; //File Handle for Windows file functions DC: HDC; //Drawing context for application Size, N: Longint; //Size of bitmap, Size of color spec P: PBitmapInfo; //Windows bitmap format info header Header: TBitmapFileHeader; //Bitmap file header Cs: PChar; PCs: Pointer; BytesRead: LongInt; begin //This procedure is based on the old LoadBitMapFile from Borland Pascal v1.5 and updated to Delphi 3 F := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, Open_Existing, 0, 0); if F = INVALID_HANDLE_VALUE then begin Result := 0; Exit; end; //Read in the Bitmap file header Pcs := Addr(Header); ReadFile(F, PCs^, SizeOf(Header), BytesRead, nil); //Standard Bitmaps have Header.bfType=$4d42 or Header.bfType = $7000 //Read the rest of the file Size := GetFileSize(F, nil) - SizeOf(TBitmapFileHeader); GetMem(P, Size); ReadFile(F, P^, Size, BytesRead, nil); N := Header.bfOffBits - SizeOf(TBitmapFileHeader); PCs := P; Cs := PCs; Cs := Cs + N; //Create the Bitmap DC := GetDC(0); Result := CreateDIBitmap(DC, P^.bmiHeader, cbm_Init, Cs, P^, dib_RGB_Colors); //Clean up ReleaseDC(0, DC); FreeMem(P, Size); CloseHandle(F); end;Step 2: Wrapper function
procedure LoadAndDisplay(DestinationWindow: THandle; BitmapFileName: String); var Dc, MemDc, Image: THandle; V: Windows.TBitmap; begin //Set up Device Contexts Dc := GetDc(DestinationWindow); MemDC := CreateCompatibleDC(DC); Image := LoadBitMapFile(BitmapFileName); //Get dimensions of bitmap GetObject(Image, SizeOf(Windows.TBitmap), @V); //Select the bitmap into memory Image := SelectObject(MemDC, Image); //Display BitBlt(DC, 0, 0, V.bmWidth, V.bmHeight, MemDC, 0, 0, MergeCopy); //Remove the BitMap from memory Image := SelectObject(MemDC, Image); //Delete Bitmap DeleteObject(Image); //Remove Device Contexts DeleteDC(MemDC); ReleaseDC(DestinationWindow, DC); end;Step 3: Apply
procedure TForm1.Button1Click(Sender: TObject); begin LoadAndDisplay(Handle, 'city.bmp'); end; |
Notes: I intentionally ignored Header.bfType fields which can be used to avoid errors like loading non-BMP files. Optimumly, you'll want a few "IF"s to make sure the user can't load a .JPG that was renamed as .BMP |