Results 1 to 10 of 16

Thread: TJPEGImage.SaveToStream problem

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1

    TJPEGImage.SaveToStream problem

    thanks, i did that and it works.
    http://atlas.walagata.com/w/peterbon...veToStream.zip
    I wrote 2 procedures to save and load a jpeg to a stream properly.

    [pascal]// save a jpeg to a memory stream with correct positioning
    procedure JPegSaveToStream(AJPG : TJPegImage ; AStream : TMemoryStream);
    Var
    LStart, LEnd : Int64;
    begin
    // store current stream position
    LStart := AStream.Position;
    // skip size of stream position
    AStream.Seek(8, LStart);
    // write the jpeg
    AJPG.SaveToStream(AStream);
    // store the new position
    LEnd := AStream.Position;
    // seek back to start position
    AStream.Position := LStart;
    // write jpeg end position to correct position when loading
    AStream.Write(LEnd, ;
    // seek back to end of stream
    AStream.Position := LEnd;
    end;

    // load a jpeg from a memory stream with correct positioning
    procedure JPegLoadFromStream(AJPG : TJPegImage ; AStream : TMemoryStream);
    Var
    LEnd : Int64;
    begin
    // load the jpeg end position
    AStream.Read(LEnd, ;
    // load the jpeg
    AJPG.LoadFromStream(AStream);
    // go to the correct end position
    AStream.Position := LEnd;
    end;[/pascal]

    seems messy though - I wish I knew why it gets the position wrong.

    Peter

  2. #2
    15 years later and I realise that my code above has an issue with loading extra data into the jpeg if the stream contains other data after the jpeg. This can cause an out of memory error if the stream is large. Fixed version is below and avoids this by copying to a new stream containing just the jpeg data.

    procedure JPegLoadFromStream(AJPG : TJPegImage ; AStream : TStream);
    Var
    LEnd : Int64;
    LMStream : TMemoryStream;
    begin
    // load the jpeg end position
    AStream.Read(LEnd, 8 );

    // Load into temporary stream as TJPeg.LoadFromStream will load to the end
    LMStream := TMemoryStream.Create;
    LMStream.CopyFrom(AStream, LEnd - AStream.Position);
    LMStream.Seek(0, soFromBeginning);

    // load the jpeg
    AJPG.LoadFromStream(LMStream);

    LMStream.Free;
    end;
    Last edited by peterbone; 29-01-2020 at 03:46 PM.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •