How do I Base64Encode a TImage in FMX application

76 views Asked by At

I need a simple way to encode the TBitmap of TImage into a base64 encoded representation for sending via JSON format. I don't want to make use of Indy libraries, instead I want to use what is built into current Delphi.

2

There are 2 answers

1
Andre Van Zuydam On

I came up with the following which is working, it returns the base64encoded string which I add as a string pair to a TJSONObject.

//use NetEncoding
function GetBase64EncodedImage(Bitmap: TBitmap): String;
var
  InputStream : TMemoryStream;
  OutputStream : TMemoryStream;
  StringList: TStringList;
begin
  InputStream := TMemoryStream.Create;
  OutputStream := TMemoryStream.Create;
  StringList := TStringList.Create;
  try
    //Save image to stream
    Bitmap.SaveToStream(InputStream);
    InputStream.Position := 0;
    //Encode the stream
    TNetEncoding.Base64.Encode( InputStream, OutputStream );
    OutputStream.Position := 0;
    StringList.LoadFromStream(OutputStream);
    Result := StringList.Text;
  finally
    InputStream.Free;
    OutputStream.Free;
    StringList.Free;
  end;
end;

I'm aware there may be a way to eliminate the TStringList, so a helpful addition or code change here to get the Stream straight to String would be good instead of having to load it to the TStringList for the result may be better.

Edited Below the refactored version as per @remy's suggestion

var
  InputStream : TMemoryStream;
  OutputStream : TStringStream;
  StringList: TStringList;
begin
  InputStream := TMemoryStream.Create;
  OutputStream := TStringStream.Create;
  try
    //Save image to stream
    Bitmap.SaveToStream(InputStream);
    InputStream.Position := 0;
    //Encode the stream
    TNetEncoding.Base64.Encode( InputStream, OutputStream );
    OutputStream.Position := 0;

    Result := OutputStream.DataString;
  finally
    InputStream.Free;
    OutputStream.Free;
  end;
end;
3
Fajar Donny Bachtiar On

you can uses this function for encode

uses unit :

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

code :

function EncodeFile(FFileLocation : String) : String;
begin
  if not FileExists(FFileLocation) then begin
    ShowMessage('File Not Exist');
    Exit;
  end;

  var Stream := TMemoryStream.Create;
  var StreamOutput := TStringStream.Create;
  try
    Stream.LoadFromFile(FFileLocation);
    Stream.Position := 0;
    TNetEncoding.Base64.Encode(Stream, StreamOutput);
    Result := StreamOutput.DataString;
  finally
    Stream.DisposeOf;
    StreamOutput.DisposeOf;
  end;
end;

and this for Decode

procedure DecodeFile(FData : String; out FStream : TMemoryStream);
begin
  var Stream := TMemoryStream.Create;
  var SL := TStringList.Create;
  try
    SL.Text := FData;
    SL.SaveToStream(Stream);
    Stream.Position := 0;

    TNetEncoding.Base64.Decode(Stream, FStream);
    FStream.Position := 0;
  finally
    SL.DisposeOf;
    Stream.DisposeOf;
  end;
end;