How to encode base64 in Delphi 6? [duplicate]

怎甘沉沦 提交于 2020-01-14 02:35:05

问题


I need to encode a pdf document to base64 in Delphi6. Can anyone help me?


回答1:


You can use the EncdDecd unit that is supplied with Delphi. The function you need is EncodeStream. You simply need to create two streams, one for input and one for output. If you are working with files then you should create TFileStream instances.

Once you have your two file streams created, all you need is:

EncodeStream(InputStream, OutputStream);



回答2:


unit base64;

interface

uses Classes;

function base64encode(f:TStream):string;

implementation

const
  Base64Codes:array[0..63] of char=
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

function base64encode(f:TStream):string;
const
  dSize=57*100;//must be multiple of 3
var
  d:array[0..dSize-1] of byte;
  i,l:integer;
begin
  Result:='';
  l:=dSize;
  while l=dSize do
   begin
    l:=f.Read(d[0],dSize);
    i:=0;
    while i<l do
     begin
      if i+1=l then
        Result:=Result+
          Base64Codes[  d[i  ] shr  2]+
          Base64Codes[((d[i  ] and $3) shl 4)]+
          '=='
      else if i+2=l then
        Result:=Result+
          Base64Codes[  d[i  ] shr  2]+
          Base64Codes[((d[i  ] and $3) shl 4) or (d[i+1] shr 4)]+
          Base64Codes[((d[i+1] and $F) shl 2)]+
          '='
      else
        Result:=Result+
          Base64Codes[  d[i  ] shr  2]+
          Base64Codes[((d[i  ] and $3) shl 4) or (d[i+1] shr 4)]+
          Base64Codes[((d[i+1] and $F) shl 2) or (d[i+2] shr 6)]+
          Base64Codes[  d[i+2] and $3F];
      inc(i,3);
      if ((i mod 57)=0) then Result:=Result+#13#10;
     end;
   end;
end;

end.



回答3:


You can use INDY's TIdEncoderMIME class to encode any file.

AFAIK, INDY 9 comes pre-installed in Delphi 6, but is advisable to update your INDY version as INDY 10 is current with lot's of improvements and bug fixes over the old INDY 9.

Your code may look like this:

uses IdCoder, IdCoder3to4, IdCoderMIME, IdBaseComponent;

procedure TForm1.Button1Click(Sender: TObject);
var
  SourceStr: TFileStream;
  Encoder: TIdEncoderMIME;
begin
  if OpenDialog1.Execute then
  begin
    SourceStr := TFileStream.Create(OpenDialog1.FileName, fmOpenRead);
    try
      Encoder := TIdEncoderMIME.Create(nil);
      try
        Memo1.Lines.Text := Encoder.Encode(SourceStr);
      finally
        Encoder.Free;
      end;
    finally
      SourceStr.Free;
    end;
  end;
end;


来源:https://stackoverflow.com/questions/14942269/how-to-encode-base64-in-delphi-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!