Delphi XE10 compress a string in base 64 with ZLIb

1


Well it turns out that I have to send from windows to mobile devices, ios and android, and vice versa, by TCP a series of data, with Embarcadero Rad Studio 10 Berlin. These data are strings in base 64 format.

So far, no problem, I send and I receive. the problem is that I need to send sometimes, a great string, and therefore, I'm looking at some method to compress the string.

I have been looking and looking at some method, and the best one, it seems to be that it is using the zlib to compress and unzip the string, and looking for this link in which it explains how to do it. The method works with normal text string, but when compressing string in base64 it takes more.

An example of a very small chain that would be sent this:

  

cEJNYkpCSThLVEh6QjNFWC9wSGhXQ3lHWUlBcGNURS83TFdDNVUwUURxRnJvZlRVUWd4WEFWcFJBNUZSSE9JRXlsaWgzcEJvTGo5anQwTlEyd1pBTEtVQVlPbXdkKzJ6N3J5ZUd4SmU2bDNBWjFEd3lVZmZTR1FwNXRqWTVFOFd2SHRwakhDOU9JUEZRM00wMWhnU0p3MWxxNFRVdmdEU2pwekhwV2thS0JFNG9WYXRDUHhTdnp4blU5Vis2ZzJQYnRIdllubzhKSFhZeUlpckNtTGtUZHVHOTFncHVUWC9FSTdOK3JEUDBOVzlaTngrcEdxcXhpRWJ1ZXNUMmdxOXpJa0ZEak1ORHBFenFVSTlCdytHTy ==

The problem is that with the length of the actual chains I send, more than 26,000 characters, when doing these tests, take up more. I do not know if you can compress these strings in any way, the truth is that in these things I am very fish.

The functions I use are these:

uses
  SysUtils, Classes, ZLib, EncdDecd;

function CompressAndEncodeString(const Str: string): string;
var
  Utf8Stream: TStringStream;
  Compressed: TMemoryStream;
  Base64Stream: TStringStream;
begin
  Utf8Stream := TStringStream.Create(Str, TEncoding.UTF8);
  try
    Compressed := TMemoryStream.Create;
    try
      ZCompressStream(Utf8Stream, Compressed);
      Compressed.Position := 0;
      Base64Stream := TStringStream.Create('', TEncoding.ASCII);
      try
        EncodeStream(Compressed, Base64Stream);
        Result := Base64Stream.DataString;
      finally
        Base64Stream.Free;
      end;
    finally
      Compressed.Free;
    end;
  finally
    Utf8Stream.Free;
  end;
end;

function DecodeAndDecompressString(const Str: string): string;
var
  Utf8Stream: TStringStream;
  Compressed: TMemoryStream;
  Base64Stream: TStringStream;
begin
  Base64Stream := TStringStream.Create(Str, TEncoding.ASCII);
  try
    Compressed := TMemoryStream.Create;
    try
      DecodeStream(Base64Stream, Compressed);
      Compressed.Position := 0;
      Utf8Stream := TStringStream.Create('', TEncoding.UTF8);
      try
        ZDecompressStream(Compressed, Utf8Stream);
        Result := Utf8Stream.DataString;
      finally
        Utf8Stream.Free;
      end;
    finally
      Compressed.Free;
    end;
  finally
    Base64Stream.Free;
  end;
end;


Thanks in advance and sorry for the sheet.

    
asked by elcharlie 20.01.2017 в 12:02
source

0 answers