Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Delphi JCL 7zCompression used to compress/decompress in-memory stream without file operations?

I had used TJcl7zCompressArchive / TJcl7zDecompressArchive to do Archive operation before.

Now I would like to compress / decompress in-memory streams directly without file operation. However, when seeing the examples from JCL demos searching in the web, I cannot find a way to do so using that lib. I did find other tools to do that but the compression ratio seems not as good as 7zip.

Can anyone give some directions or sample code showing how to achieve this. Thanks a lot!

like image 247
Justmade Avatar asked Aug 09 '11 14:08

Justmade


1 Answers

I use the JCL wrapper to compress a GZIP stream - not sure if it would work simply using a TJcl7ziCompresspArchive. To compress a stream I use the following:

procedure _CompressStreamGZIP( const ASourceStream, ADestinationStream: TStream );
var
  LArchive : TJclCompressArchive;
begin
  ADestinationStream.Position := 0;
  ASourceStream.Position := 0;
  LArchive := TJclGZipCompressArchive.Create( ADestinationStream, 0, False );

  try
    LArchive.AddFile( '..\Stream.0', ASourceStream, false );
    LArchive.Compress();
  finally
    if ( Assigned( LArchive ) ) then FreeAndNil( LArchive );
  end;
end;

To decompress the stream:

procedure _DecompressStreamGZIP( const ASourceStream, ADestinationStream : TStream );
var
  LArchive : TJclDecompressArchive;
begin
  ADestinationStream.Position := 0;
  ASourceStream.Position := 0;
  LArchive := TJclGZipDecompressArchive.Create( ASourceStream, 0, false );

  try
    LArchive.ListFiles();
    LArchive.Items[0].Stream := ADestinationStream;
    LArchive.Items[0].OwnsStream := false;
    LArchive.Items[0].Selected := True;
    LArchive.ExtractSelected();
  finally
    if ( Assigned( LArchive ) ) then FreeAndNil( LArchive );
  end;
end;
like image 124
berndvf Avatar answered Nov 10 '22 20:11

berndvf