使用 Delphi 2007 将 Base64 字符串作为二进制文件保存到磁盘 [英] Saving a Base64 string to disk as a binary using Delphi 2007
问题描述
我有一个 Base64 二进制字符串,它是由第 3 方供应商发送给我们的 XML 文档的一部分,我希望能够将其保存回原始文件格式 (jpg).
I have a Base64 binary string that is part of an XML document that is sent to us by a 3rd party supplier, I would like to be able to save it back to its original file format (jpg).
使用此问题的已接受答案 使用 php 将 base64 字符串作为二进制文件保存到磁盘" 我可以毫不费力地将字符串保存为 jpg,因此我知道该字符串的格式很好并且是 JPG 文件.
Using the accepted answer from this question "saving a base64 string to disk as a binary using php" I can save the string to a jpg with little effort, so I know the string is in good form and is a JPG file.
但是我如何在 Delphi 2007 中做到这一点?
But how do I do this in Delphi 2007?
在网上我找到了一个关于如何将 Base64 转换为 TByteDynArray 的教程,并保存它,但它不能正常工作.我也玩过 Indy 的 IdDecoderMIME,但没有成功.
Looking on the net I found a tutorial on how to convert the Base64 into a TByteDynArray, and save that, but it doesn't work right. I have also played about with Indy's IdDecoderMIME, but with with no success.
有谁知道怎么做,或者我应该去哪里找?
Does any one know how to do this, or where I should be looking?
推荐答案
来自 OmniXML 项目的 OmniXMLUtils.pas包含以下功能:
OmniXMLUtils.pas from the OmniXML project contains following functions:
function Base64Decode(encoded, decoded: TStream): boolean; overload;
function Base64Decode(const encoded: string; decoded: TStream): boolean; overload;
function Base64Decode(const encoded: string; var decoded: string): boolean; overload;
function Base64Decode(const encoded: string): string; overload;
procedure Base64Encode(decoded, encoded: TStream); overload;
procedure Base64Encode(decoded: TStream; var encoded: string); overload;
function Base64Encode(decoded: TStream): string; overload;
function Base64Encode(const decoded: string): string; overload;
procedure Base64Encode(const decoded: string; var encoded: string); overload;
Base64Decode(string, TStream) 应该可以解决问题.对于 TStream 参数,您可以像这样传递 TFileStream:
The Base64Decode(string, TStream) should do the trick. For the TStream parameter you can pass it TFileStream like this:
procedure SaveBase64ToFile(const encoded, fileName: string);
var
fs: TFileStream;
begin
fs := TFileStream.Create(fileName, fmCreate);
try
if not Base64Decode(encoded, fs) then
raise Exception.Create('Invalid data!');
finally FreeAndNil(fs); end;
end;
这篇关于使用 Delphi 2007 将 Base64 字符串作为二进制文件保存到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!