Delphi xe2 encode/decode base 64

15,443

You are not specifying what kind of data are you trying to encode or decode. The DecodeBase64 and EncodeBase64 functions uses the EncodeStream and DecodeStream internally, in theory you can use these functions based on streams to encode or decode any type or data (after of use a stream to hold the data).

For encode/decode strings just use the EncodeString and DecodeString functions directly.

function  EncodeString(const Input: string): string;
function  DecodeString(const Input: string): string;

For streams use EncodeStream and DecodeStream

procedure EncodeStream(Input, Output: TStream);
procedure DecodeStream(Input, Output: TStream);

Sample for EncodeBase64

function  DecodeBase64(const Input: AnsiString): TBytes;
function  EncodeBase64(const Input: Pointer; Size: Integer): AnsiString;

For example to encode a file and return a string using the EncodeBase64 function you can try this (obviously you can use EncodeStream function directly too).

function EncodeFile(const FileName: string): AnsiString;
var
  LStream: TMemoryStream;
begin
  LStream := TMemoryStream.Create;
  try
    LStream.LoadFromFile(Filename);
    Result := EncodeBase64(LStream.Memory, LStream.Size);
  finally
    LStream.Free;
  end;
end;

Now to use the DecodeBase64 function just pass an already encoded string and the function will return a TBytes (array of bytes).

Share:
15,443
img.simone
Author by

img.simone

Updated on June 04, 2022

Comments

  • img.simone
    img.simone almost 2 years

    Can someone provide me with an example of how to use EncodeBase64 and DecodeBase64 from library Soap.EncdDecd? I'm Using Delphi xe2

  • img.simone
    img.simone almost 11 years
    Hello, thanks for your example, but it doesn't work. When passing a string, there is an error message: "Cannot open the specific file (the path). The system cannot find the path specified". Who do I solve?
  • RRUZ
    RRUZ almost 11 years
    That is because the file doesn't exist. if you want encode a string just use the EncodeString function.