How to convert an encoded64 file to binary format?


I have an encoded64 string parameter of a RO server method (representing a png file) which I would like to save in a file.
My first attempt was to just save it. It saved OK but no one could use it (as it was not native format, just a bunch of characters).
So, I converted it using this function:

  System.NetEncoding, System.Classes, System.SysUtils;

function ConvertBase64EncodedPNGToBinary(const Base64String: string): TByteStream;
  DecodedStream: TBytesStream;
  EncodedBytes: TBytes;
  // Convert the Base64 string to bytes
  EncodedBytes := TNetEncoding.Base64.DecodeStringToBytes(Base64String);

  // Create a stream from the decoded bytes
  result := TBytesStream.Create(EncodedBytes);

My server function (the function that will save it to a file) is the following:

procedure SaveFile(file: Binary; ...other parameters);

Delphi complains that incompatible format TRoMemoryBinaryStream and TBytesStream. The problem is I don’t know how to feed a TRoMemoryBinaryStream (Binary) with a TBytes (decoded64) array.

Could you help me?


TROMemoryBinaryStream (aka Binary) is a descendant of standard TStream so you can use standard TStream methods for filling Binary data like

    function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; overload; virtual;
    function Write(const Buffer: TBytes; Count: Longint): Longint; overload;
    function Write64(const Buffer: TBytes; Offset, Count: Int64): Int64; virtual;
    function WriteData(const Buffer: TBytes; Count: NativeInt): NativeInt; overload;
    procedure WriteBuffer(const Buffer: TBytes; Count: NativeInt); overload;
    procedure WriteBuffer(const Buffer: TBytes; Offset, Count: NativeInt); overload;

Also you can use our methods that work with base64:

procedure EncodeStream(anInputStream, anOutputStream: TStream; aAddLineBreak: Boolean = True);
procedure DecodeStream(anInputStream, anOutputStream: TStream);

function EncodeString(anInput: UnicodeString): ROAnsiString;
function DecodeString(anInput: ROAnsiString): UnicodeString;

function EncodeBytesToString(anInput: TBytes): ROAnsiString;
function DecodeStringToBytes(anInput: ROAnsiString): TBytes;

Thanks, it worked using:

decoded := TRoBinaryMemoryStream.Create();
decoded.write(encodedBytes, length(encodedBytes));

Wonderful support as always.