红鱼儿

用原生TBase64Encoding实现文件与Base64串互相转换

将一个文件转换成Base64编码串:

function FileToBase64(fn: string): string;
var
  msSource: TMemoryStream;
  msTarget: TStringStream;
  str: string;
  base64: TBase64Encoding;
begin
  msSource := TMemoryStream.Create;
  msTarget := TStringStream.Create('');
  try
    msSource.LoadFromFile(fn);
    base64 := TBase64Encoding.Create(0); //0: 不填加回车换行符
    base64.Encode(msSource, msTarget);   
    result := msTarget.DataString;
  finally
    msSource.Free;
    msTarget.Free;
  end;
end;

将一个Base64串转换成文件:

procedure Base64ToFile(ASource: string; fn: string);
var
  msSource: TStringStream;
  msTarget: TMemoryStream;
  base64: TBase64Encoding;
begin
  msSource := TStringStream.Create(ASource);
  msTarget := TMemoryStream.Create;
  try
    base64 := TBase64Encoding.Create(0); // 0: 不填加回车换行符
    base64.Decode(msSource, msTarget);
    msTarget.SaveToFile(fn);
  finally
    msSource.Free;
    msTarget.Free;
  end;
end;

将一个Base64串转换成流:

procedure Base64ToStream(ASource: string; AStream: TMemoryStream);
var
  msSource: TStringStream;
  base64: TBase64Encoding;
begin
  msSource := TStringStream.Create(ASource);
  try
    base64 := TBase64Encoding.Create(0); // 0: 不填加回车换行符
    base64.Decode(msSource, AStream);
  finally
    msSource.Free;
  end;
end;

下面是测试代码:

procedure TForm12.Button1Click(Sender: TObject);
var
  s: string;
  fn, fn1: string;
begin
  if OpenPictureDialog1.Execute(Self.Handle) then
  begin
    fn := OpenPictureDialog1.FileName;

    fn1 := TPath.Combine(TPath.GetDirectoryName(fn), TPath.GetGUIDFileName+'.jpg');

    s := FileToBase64(fn);
    Base64ToFile(s, fn1);

    Memo1.Lines.Clear;
    // Memo1.Lines.Add(s);
  end;
end;

别忘记引用单元:System.NetEncoding,  System.IOUtils

Delphi 10.4.2测试通过。

 

posted on 2022-03-24 16:12  红鱼儿  阅读(1201)  评论(1编辑  收藏  举报