Kamis, 25 Januari 2024

Compress and Decompress Text or File using ZLib in Delphi or Free Pascal Lazarus

When I was in my college I work as part time programmer in a software house. I got a task to create a software updater. The software updater work by copying new files to the already installed application in the client's computers. To make update file easier to distribute I need to compress the new files and combine them into a file.

In Delphi or Lazarus we can use TFileStream class to access files and using TCompressionStream in the zstream unit to compress data from memory buffer to output stream that can be any TStream object including TFileStream or TMemoryStream. To decompress later you can use TDecompressionStream class.

If ZLib compression is not enough you can use BZip2 library for stronger compression.

Bellow is an example of using ZLib TCompressionStream and TDecompressionStream class:

  1. program TestCompressAndDecompress;
  2. {$MODE DELPHI}
  3. uses SysUtils, Classes, zstream;
  4. var
  5.   F: TMemoryStream;
  6.   Comp: TCompressionStream;
  7.   Decomp: TDecompressionStream;
  8.   X, Y: AnsiString;
  9. begin
  10.   F := TMemoryStream.Create;
  11.   try
  12.     Comp := TCompressionStream.Create(clMax, F);
  13.    try
  14.       X := 'Compress and Decompress array of bytes or a file using ZLib in Delphi or Free Pascal Lazarus';
  15.       Comp.Write(X[1], Length(X));
  16.     finally
  17.       Comp.Free;
  18.     end;
  19.     WriteLn('Original Text: "',X,'"');
  20.     WriteLn('Original Size: ',Length(X),' bytes.');
  21.     WriteLn('Compressed Size: ',F.Size,' bytes.');
  22.     F.Position := 0;
  23.     Decomp := TDecompressionStream.Create(F);
  24.     try
  25.        SetLength(Y, Length(X));
  26.        Decomp.Read(Y[1], Length(Y));
  27.     finally
  28.       Decomp.Free;
  29.     end;
  30.     WriteLn('Decompressed Text: "',Y,'"');
  31.   finally
  32.     F.Free;
  33.   end;
  34. end.

Tidak ada komentar:

Creating Linux Daemon or Windows Service with Lazarus

Daemon Application in Linux or Service Application in Windows is an application that running in the background, usually automatically starte...