2

我正在执行以下操作以将 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 字符串会导致内存不足。

4

1 回答 1

4

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

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;
于 2016-06-02T22:09:27.373 回答