在 Delphi 10.4 中,我TPicture
使用以下代码成功地将有效的 base64 编码保存到 INI 文件中:
procedure TForm1.SavePictureToIniFile(const APicture: TPicture);
// https://stackoverflow.com/questions/63216011/tinifile-writebinarystream-creates-exception
var
LInput: TMemoryStream;
MyIni: TMemIniFile;
Base64Enc: TBase64Encoding;
ThisFile: string;
begin
if FileSaveDialog1.Execute then
ThisFile := FileSaveDialog1.FileName
else EXIT;
//CodeSite.Send('TForm1.btnSaveToIniClick: VOR Speichern');
LInput := TMemoryStream.Create;
try
APicture.SaveToStream(LInput);
LInput.Position := 0;
MyIni := TMemIniFile.Create(ThisFile);
try
Base64Enc := TBase64Encoding.Create(Integer.MaxValue, '');
try
MyIni.WriteString('Custom', 'IMG', Base64Enc.EncodeBytesToString(LInput.Memory, LInput.Size));
finally
Base64Enc.Free;
end;
MyIni.UpdateFile;
finally
MyIni.Free;
end;
finally
LInput.Free;
end;
//CodeSite.Send('TForm1.btnSaveToIniClick: NACH Speichern'); // 0,024 Sek.
end;
现在我想反转这个过程,即将数据从 INI 文件加载回TPicture
:
procedure TForm1.btnLoadFromIniClick(Sender: TObject);
var
LInput: TMemoryStream;
LOutput: TMemoryStream;
ThisFile: string;
MyIni: TMemIniFile;
Base64Enc: TBase64Encoding;
ThisEncodedString: string;
ThisPicture: TPicture;
begin
if FileOpenDialog1.Execute then
ThisFile := FileOpenDialog1.FileName
else EXIT;
MyIni := TMemIniFile.Create(ThisFile);
try
Base64Enc := TBase64Encoding.Create(Integer.MaxValue, '');
try
(*ThisEncodedString := MyIni.ReadString('Custom', 'IMG', '');
Base64Enc.Decode(ThisEncodedString); // And now???*)
LInput := TMemoryStream.Create;
LOutput := TMemoryStream.Create;
try
MyIni.ReadBinaryStream('Custom', 'IMG', LInput);
MyIni.UpdateFile;
LInput.Position := 0;
Base64Enc.Decode(LInput, LOutput);
LOutput.Position := 0;
ThisPicture := TPicture.Create;
try
ThisPicture.LoadFromStream(LOutput);
CodeSite.Send('TForm1.btnLoadFromIniClick: ThisPicture', ThisPicture); // AV!
finally
ThisPicture.Free;
end;
finally
LOutput.Free;
LInput.Free;
end;
finally
Base64Enc.Free;
end;
finally
MyIni.Free;
end;
end;
但是当发送图片时CodeSite.Send
会创建一个 AV!(发送一个TPicture
通常CodeSite.Send
确实有效,在这种情况下,AV 显然意味着图片已损坏)。
那么如何将数据从 INI 文件加载回TPicture
?