Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

serialization - How to encode file of any type into base64 string and then decode it into file again using Lazarus/Delphi?

Can you tell me how can I do that? Is there any Freepascal unit that can do this for me? I need that so my program can store binary data in it's XML-based fileformat.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the base64 unit and its two classes, TBase64EncodingStream and TBase64DecodingStream.

Here is a 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.

And, in the 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.

or the shorthands encodestringbase64 and decodestringbase64 (2.4.4+) for non stream based usage:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...