Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize Delphi code for image decoding?

I have encoded images and want to decode them in my program. The images decoding is based on the answer of Loren Pechtel: the image file is loaded in Stream, decoded, converted to MemoryStream and then loaded from MemoryStream by TSynPicture class. The Delphi code is the following:

function loadEncodedImage(filename, keycode : string) : TBitmap;
  syn : TSynPicture;
  fs  : TFileStream;
  ms  : TMemoryStream;
  buf : AnsiString;
begin
  result := nil;
  try
    fs := TFileStream.Create(filename, fmOpenRead);
    SetLength( buf, fs.Size );
    fs.ReadBuffer( buf[1], fs.Size );

    // ....
    // Here I decode data stored in buf and put it into buf again.
    // ....

    ms := TMemoryStream.Create();
    ms.SetSize( fs.Size );
    ms.WriteBuffer( buf[1], fs.Size );

    syn := TSynPicture.Create();
    syn.LoadFromStream( ms );
    result := syn.ToBitmap;
  finally
    FreeAndNil( fs );
    FreeAndNil( syn );
   end;
end;

As you see I use two buffers of memory: buf and TMemoryStream. How this code can be optimized to avoid double memory use?

like image 510
Ivan Z Avatar asked Jan 23 '26 02:01

Ivan Z


1 Answers

TMemoryStream has a Memory member allowing directly accessing the memory block. This way you can completely eliminate buf.

like image 87
JensG Avatar answered Jan 25 '26 02:01

JensG