我有一个Base64包含 PDF 数据的编码字符串。使用 EncdDecd
单元我可以将字符串解码为字节数组。
这就是我遇到麻烦的地方:我尝试将字符保存到字符串中,但是一旦它达到零值(ASCII = 0
或 #0
或 $00
) 字符串不再附加。示例:
uses
EncdDecd;
var
EncodedString : String;
Report : String;
Base64Bytes: TBytes; // contains the binary data
begin
Base64Bytes := DecodeBase64(EncodedString);
for I := 0 to Length(Base64Bytes) - 1 do
begin
Report := Report + Chr(Base64Bytes[I]);
end;
写入文本文件似乎效果更好,但将其重命名为 .PDF
后,文件无法正确打开。
如何在 Delphi 中写入二进制文件?或者甚至将数据保存到流中?基本上我只是想获取编码的字符串并将其保存到 PDF/二进制文件,或在 Delphi 中显示 PDF。
我环顾四周并找到了一个可能的解决方案 Saving a Base64 string to disk as a binary using Delphi 2007但还有其他方法吗?
最佳答案
这应该可以做到:
procedure DecodeBaseToFile(const FileName: string;
const EncodedString: AnsiString);
var
bytes: TBytes;
Stream: TFileStream;
begin
bytes := DecodeBase64(EncodedString);
Stream := TFileStream.Create(FileName, fmCreate);
try
if bytes<>nil then
Stream.WriteBuffer(bytes[0], Length(bytes));
finally
Stream.Free;
end;
end;
注意:我只是在脑海中编译了这个。
关于arrays - Base64编码的字符串到二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7956541/