Examples Delphi

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;