Sample code for 30+ languages & platforms
Delphi DLL

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 DLL Downloads

Delphi DLL
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Gzip, StringBuilder, BinData;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
gzip: HCkGzip;
sb: HCkStringBuilder;
bd: HCkBinData;

begin
success := False;

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

gzip := CkGzip_Create();
sb := CkStringBuilder_Create();
bd := CkBinData_Create();

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

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

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

// (Optional) Save to a .gz file:
success := CkBinData_WriteFile(bd,'text.gz');
if (success = False) then
  begin
    Memo1.Lines.Add(CkBinData__lastErrorText(bd));
    Exit;
  end;

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

CkGzip_Dispose(gzip);
CkStringBuilder_Dispose(sb);
CkBinData_Dispose(bd);

end;