DelphiFAQ Home Search:
General :: Programming :: Delphi :: VCL
About the Delphi VCL (Visual Component Library)

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Only the 40 most recently viewed articles are shown.
You can see the full list here.

Featured Article

Streaming out multiple pictures (any raw data)

Problem:
// After streaming out 2 jpegs, the second one cannot be read
ms := TMemoryStream.Create;
JPG1.SaveToStream(ms);
JPG2.SaveToStream(ms);

ms.Seek(0,0);
JPG1.LoadFromStream(ms);
// now it is at the end of the stream
// and JPG2 won't be read

JPG2.LoadFromStream(ms);

Solution:
Store the length of each graphic (raw data blob) before the data.
Use this value when reading from the stream.

procedure SavePicture(Stream: TStream; gr: TGraphic);
 var
   P,
   newp: integer;
 begin
   P := Stream.Position;
   Stream.WriteBuffer(P, sizeof(P));
   gr.SaveToStream(Stream);
   newp := Stream.Position;
   Stream.Position := P;
   P := newp-P-sizeof(P);
   Stream.WriteBuffer(P, sizeof(P));
   Stream.Position := newp;
 end;
 
 
 procedure LoadPicture(Stream: TStream; gr: TGraphic);
 var
   MemStream: TMemoryStream;
   v        : integer;
 begin 
   MemStream := TMemoryStream.Create; 
   try 
     Stream.ReadBuffer(v, sizeof(v)); 
     MemStream.SetSize(v); 
     Stream.ReadBuffer((MemStream.Memory)^, v); 
     MemStream.Position := 0; 
     gr.LoadFromStream(MemStream); 
   finally 
     MemStream.Free; 
   end; 
 end; 
 
You don't like the formatting? Check out SourceCoder then!
Generated 16:01:49 on Mar 27, 2017