String Delphi通过TBitmapSurface将TBitmap转换为字符串并返回TBitmap

String Delphi通过TBitmapSurface将TBitmap转换为字符串并返回TBitmap,string,delphi,firemonkey,tbitmap,String,Delphi,Firemonkey,Tbitmap,我正在执行以下操作以将TBitmap(Firemonkey)转换为字符串: function BitmapToBase64(Bitmap: Tbitmap): string; var BS: TBitmapSurface; AStream: TMemoryStream; begin BS := TBitmapSurface.Create; BS.Assign(Bitmap); BS.SetSize(300, 200); AStream := TMemoryStream.C

我正在执行以下操作以将TBitmap(Firemonkey)转换为字符串:

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;
如何将字符串还原回TBitmap?我做了以下不生成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;
我需要较小大小的base64字符串,以便将其传输到Datasnap服务器。当字符串长度超过200000-1000000时,正常的base64字符串会导致内存不足。

BitmapToBase64()
中,您将
TMemoryStream
本身传递给
TNetEncoding.base64.EncodeBytesToString()
,它不接受流作为开始的输入。您需要传递流的
内存
属性的值:

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.Memory, AStream.Size);
  finally
    AStream.Free;
    BS.Free;
  end;
end;

@Johan:将位图保存为PNG格式的代码,然后对PNG进行base64编码,然后对其进行解码,最后将其加载到位图中。唯一涉及的字符串是base64。@TomBrunberg base64将解码为PNG,TbitMapCodeManager可以加载PNG。哎哟,很抱歉发出噪音。让我们整理一下不相关的评论。Base64ToBitmap呢?字符串没问题,现在我需要返回TBitmap。@shariful,我认为Base64ToBitmap()没有任何问题,但我对使用TBitmapSurface不太熟悉。Remy,BitmapToBase64的流大小和Base64ToBitmap的流大小不一样,你注意到了吗?这就是为什么没有分配TBitmap的原因吗?@shariful没有,我没有注意到,因为我没有运行代码。Base64是一种无损格式,它解码到与编码相同的大小,因此TNetEncoding.Base64可能已损坏,或者发生了其他情况。大小的实际差异是什么?您是否将原始字节与解码的字节进行比较以寻找差异?