gpt4 book ai didi

string - Delphi TBitmap 通过 TBitmapSurface 到字符串并返回到 TBitmap

转载 作者:行者123 更新时间:2023-12-02 06:34:32 24 4
gpt4 key购买 nike

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

关于string - Delphi TBitmap 通过 TBitmapSurface 到字符串并返回到 TBitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37602538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com