如何将任何类型的文件编码为base64字符串,然后使用Lazarus / Delphi将其解码为文件?

时间:2012-04-20 08:14:55

标签: delphi serialization base64 freepascal lazarus

你能告诉我怎么办?是否有任何Freepascal单位可以为我做这个?我需要这样,所以我的程序可以将二进制数据存储在基于XML的文件格式中。

1 个答案:

答案 0 :(得分:9)

使用base64单元及其两个类TBase64EncodingStreamTBase64DecodingStream

这是simple example

program demo;

uses Classes, base64;

var
  DecodedStream: TStringStream;
  EncodedStream: TStringStream;
  Encoder: TBase64EncodingStream;
  Output: string;
begin
  DecodedStream := TStringStream.Create('Hello World!');
  EncodedStream := TStringStream.Create('');
  Encoder       := TBase64EncodingStream.Create(EncodedStream);
  Encoder.CopyFrom(DecodedStream, DecodedStream.Size);

  Output := EncodedStream.DataString;
  { Outputs 'SGVsbG8gV29ybGQh' }
  WriteLn(Output);

  DecodedStream.Free;
  EncodedStream.Free;
  Encoder.Free;
end.

而且,在opposite direction

program demo;

uses Classes, base64;

var
  DecodedStream: TStringStream;
  EncodedStream: TStringStream;
  Decoder: TBase64DecodingStream;
  Output: string;
begin
  EncodedStream := TStringStream.Create('SGVsbG8gV29ybGQh');
  DecodedStream := TStringStream.Create('');
  Decoder       := TBase64DecodingStream.Create(EncodedStream);
  DecodedStream.CopyFrom(Decoder, Decoder.Size);

  Output := DecodedStream.DataString;
  { Outputs 'Hello World!' }
  WriteLn(Output);

  DecodedStream.Free;
  EncodedStream.Free;
  Decoder.Free;
end.

或简写encodestringbase64decodestringbase64(2.4.4+)用于非基于流的用法:

Uses Base64;
var 
   s : AnsiString;
Begin
  s:=EncodeStringBase64('Hello world!');
  Writeln('Encoded : ',s);
  s:=DecodeStringBase64(s);
  Writeln('Decoded again : ',s);    
end.