Converting large file to base64 with Delphi

I need to convert a 480mb file to base64, but I can't. I always get a message from memory. 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;

      

+3


source to share


1 answer


You don't have to keep the entire Base64 string in memory. 480MB encoded in Base64 would result in roughly 640M characters, which takes up about 1.28GB of memory. This is due to a failure in a 32 bit application.

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



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;

      

+6


source







All Articles