我正在执行以下操作将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;