Delphi TBitmap to string via TBitmapSurface and back to TBitmap

  

I am doing following to convert TBitmap(Firemonkey) to string:

function BitmapToBase64(Bitmap: Tbitmap): string;
var
BS: TBitmapSurface;
AStream: TMemoryStream;
begin
BS := TBitmapSurface.Create;
BS.Assign(Bitmap);
BS.SetSize(300, 200);
AStream := TMemoryStream.Create;
try
TBitmapCodecManager.SaveToStream(AStream, BS, ‘.png’);
Result := TNetEncoding.Base64.EncodeBytesToString(AStream, AStream.Size);
finally
AStream.Free;
BS.Free;
end;
end;

How can I revert the string back to TBitmap? I did following which doesn’t produce TBitmap:

procedure Base64ToBitmap(AString: String; Result : Tbitmap);
var
ms : TMemoryStream;
BS: TBitmapSurface;
bytes : TBytes;
begin
bytes := TNetEncoding.Base64.DecodeStringToBytes(AString);
ms := TMemoryStream.Create;
try
ms.WriteData(bytes, Length(bytes));
ms.Position := 0;
BS := TBitmapSurface.Create;
BS.SetSize(300, 200);
try
TBitmapCodecManager.LoadFromStream(ms, bs);
Result.Assign(bs);
finally
BS.Free;
end;
finally
ms.Free;
end;
end;

I need smaller size of base64 string so that I can transmit it to Datasnap server. Normal base64 string gives me Out of memory as size of string goes greater then 200000 – 1000000 in length.

Comments are closed.