Convert large file to base64 with Delphi

oTTo Mostaert picture oTTo Mostaert · Apr 27, 2017 · Viewed 7k times · Source

I need to convert a file from 480mb to base64, but I can not. I always get out of memory message. Would anyone have any suggestions?

function TFormService.LoadFileToBase64(const AFileName: string): String;
var
//  stream: TMemoryStream;
  Encoder: TIdEncoderMIME;
  Base64String: String;
  LStream: TMemoryStream;
begin
  Encoder := TIdEncoderMIME.Create;
  LStream := TMemoryStream.Create;
  try
    LStream.LoadFromFile(AFileName);
    Base64String := Encoder.Encode(LStream);
  finally
    FreeAndNil(Encoder);
    FreeAndNil(LStream);
  end; // try finally


//  stream := TMemoryStream.Create;
//  try
//    stream.LoadFromFile(AFilename);
//    result := EncodeBase64(stream.Memory, stream.Size);
//  finally
//    stream.Free;
//  end;
end;

Answer

Uwe Raabe picture Uwe Raabe · Apr 27, 2017

You should not hold the whole Base64 string in memory. 480 MB encoded to Base64 will result in about 640 M chars, which occupy about 1.28 GB memory. This is bound to fail in a 32 bit application.

Better write the encoded string to a file and use a proper encoder for that. Recent Delphi versions have System.NetEncoding for that:

procedure ConvertFileToBase64(const AInFileName, AOutFileName: string);
var
  inStream: TStream;
  outStream: TStream;
begin
  inStream := TFileStream.Create(AInFileName, fmOpenRead);
  try
    outStream := TFileStream.Create(AOutFileName, fmCreate);
    try
      TNetEncoding.Base64.Encode(inStream, outStream);
    finally
      outStream.Free;
    end;
  finally
    inStream.Free;
  end;
end;