Sample code for 30+ languages & platforms
PureBasic

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

PureBasic
IncludeFile "CkBinData.pb"
IncludeFile "CkGzip.pb"
IncludeFile "CkStringBuilder.pb"

Procedure ChilkatExample()

    success.i = 0

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

    gzip.i = CkGzip::ckCreate()
    If gzip.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    sb.i = CkStringBuilder::ckCreate()
    If sb.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    bd.i = CkBinData::ckCreate()
    If bd.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Add some text to the StringBuilder:
    CkStringBuilder::ckAppend(sb,"The quick brown fox jumps over the lazy dog.")

    ; Compress the text using UTF-8 encoding:
    success = CkGzip::ckCompressSb(gzip,sb,"utf-8",bd)
    If success = 0
        Debug CkGzip::ckLastErrorText(gzip)
        CkGzip::ckDispose(gzip)
        CkStringBuilder::ckDispose(sb)
        CkBinData::ckDispose(bd)
        ProcedureReturn
    EndIf

    ; The BinData now contains the Gzip-compressed bytes.
    Debug "Compression successful."
    Debug "Compressed size (bytes): " + Str(CkBinData::ckNumBytes(bd))

    ; (Optional) Save to a .gz file:
    success = CkBinData::ckWriteFile(bd,"text.gz")
    If success = 0
        Debug CkBinData::ckLastErrorText(bd)
        CkGzip::ckDispose(gzip)
        CkStringBuilder::ckDispose(sb)
        CkBinData::ckDispose(bd)
        ProcedureReturn
    EndIf

    Debug "Gzip file written to text.gz"


    CkGzip::ckDispose(gzip)
    CkStringBuilder::ckDispose(sb)
    CkBinData::ckDispose(bd)


    ProcedureReturn
EndProcedure