Delphi TBitmap 通过 TBitmapSurface 字符串并返回 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.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 服务器。正常的 base64 字符串给我内存不足,因为字符串的大小大于 200000 - 1000000 的长度。

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;

相关内容

  • 没有找到相关文章

最新更新