Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Compress Large Binary File in Blocks

See more Compression Examples

Compresses a large binary file in blocks.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Compression,
  Chilkat.FileAccess;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  facSrc: TFileAccess;
  facDest: TFileAccess;
  blockSize: Integer;
  numBlocks: Integer;
  compress: TCompression;
  fileBytes: TBytes;
  compressedBytes: TBytes;
  i: Integer;

begin
  success := False;

  //  This example assumes the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  facSrc := TFileAccess.Create;
  facDest := TFileAccess.Create;

  //  Open a large binary file for reading.
  success := facSrc.OpenForRead('qa_data/bmp/big.bmp');
  if (success = False) then
    begin
      WriteLn(facSrc.LastErrorText);
      Exit;
    end;

  //  If we compress in 64K chunks, find out how many blocks there will be.
  blockSize := 65536;
  numBlocks := facSrc.GetNumBlocks(blockSize);

  //  Open an output file for the compressed data.
  success := facDest.OpenForWrite('c:/temp/qa_output/compressedBmp.dat');
  if (success = False) then
    begin
      WriteLn(facDest.LastErrorText);
      Exit;
    end;

  compress := TCompression.Create;
  compress.Algorithm := 'deflate';

  //  Assuming numBlocks > 1
  compress.FirstChunk := True;
  compress.LastChunk := False;

  i := 0;
  while i < numBlocks do
    begin
      fileBytes := facSrc.ReadBlock(i,blockSize);
      compressedBytes := compress.CompressBytes(fileBytes);

      facDest.FileWrite(compressedBytes);

      i := i + 1;

      compress.FirstChunk := False;
      if (i = (numBlocks - 1)) then
        begin
          compress.LastChunk := True;
        end;
    end;

  facSrc.FileClose();
  facDest.FileClose();

  WriteLn('Finished compressing file.');


  facSrc.Free;
  facDest.Free;
  compress.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.