Sample code for 30+ languages & platforms
Delphi ActiveX

Compress Text from StringBuilder to Gzip (BinData Output)

See more Gzip Examples

This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.

The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.

This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.

Chilkat Delphi ActiveX Downloads

Delphi ActiveX
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Chilkat_TLB;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Integer;
gzip: TChilkatGzip;
sb: TChilkatStringBuilder;
bd: TChilkatBinData;

begin
success := 0;

// This example demonstrates how to compress text contained in a StringBuilder
// into Gzip format, storing the compressed result in a BinData object.

gzip := TChilkatGzip.Create(Self);
sb := TChilkatStringBuilder.Create(Self);
bd := TChilkatBinData.Create(Self);

// Add some text to the StringBuilder:
sb.Append('The quick brown fox jumps over the lazy dog.');

// Compress the text using UTF-8 encoding:
success := gzip.CompressSb(sb.ControlInterface,'utf-8',bd.ControlInterface);
if (success = 0) then
  begin
    Memo1.Lines.Add(gzip.LastErrorText);
    Exit;
  end;

// The BinData now contains the Gzip-compressed bytes.
Memo1.Lines.Add('Compression successful.');
Memo1.Lines.Add('Compressed size (bytes): ' + IntToStr(bd.NumBytes));

// (Optional) Save to a .gz file:
success := bd.WriteFile('text.gz');
if (success = 0) then
  begin
    Memo1.Lines.Add(bd.LastErrorText);
    Exit;
  end;

Memo1.Lines.Add('Gzip file written to text.gz');
end;