UnitUnit1;InterfaceusesWindows, Messages, sysutils, variants, Classes, Graphics, Controls, Forms, Dialogs, Stdctrls;typeTForm1 =class(Tform) Button1:tbutton; Button2:tbutton;procedureButton1Click (Sender:tobject);procedureButton2click (Sender:tobject);End;varForm1:tform1;Implementation{$R *.DFM}usesZlib;{Compressed stream tcompressionstream and decompressed stream tdecompressionstream from Zlib unit}//CompressionprocedureTform1.button1click (Sender:tobject);varCs:tcompressionstream;{define compressed stream}Fs,ms:tmemorystream;{FS is the stream to compress; MS is the stream that receives the compressed file}Num:integer;{Original file size}begin{First step: Dial in the file to be compressed and get the size}FS: = Tmemorystream.create; Fs. LoadFromFile (' C:\temp\test.txt ');{file to exist}Num: = fs. Size;{Step Two: Create the received stream and write the original file size first}MS: = Tmemorystream.create; Ms. Write (num, SizeOf (num));{step three: Compress}CS: = Tcompressionstream.create (CLmax, MS);{Parameter 1 is the compression ratio; parameter 2 is the receive stream}Fs. Savetostream (CS);{incoming data to compress}Cs. Free;{The compressed stream does not actually complete the compression, so advance free}{Fourth step: Save}Ms. SaveToFile (' c:\temp\test.zipx ');{Fifth step: release}Ms. Free; Fs. Free;{Compression Ratio parameter: Clnone uncompressed clfastest fast cldefault default CLmax maximum scale}End;//UnzipprocedureTform1.button2click (Sender:tobject);varDs:tdecompressionstream;{Extract Stream}Fs,ms:tmemorystream;{FS is the stream ready to decompress; MS is the stream that accepts the extracted data}Num:integer;{Accept the size before file compression}begin{First step: The file to be unzipped}FS: = Tmemorystream.create; Fs. LoadFromFile (' c:\temp\test.zipx ');{must be a file generated by the previous compression method}{Step Two: Read the size before the file is compressed}Fs. Position: =0; Fs. Readbuffer (num,sizeof (num));{Step Three: Prepare the stream to be received and set the desired size}MS: = Tmemorystream.create; Ms. SetSize (num);{Fourth step: unzip}DS: = Tdecompressionstream.create (FS);{parameter is the stream to decompress}{Step Fifth: Read the extracted data to the stream that is ready to be received}Ds. Read (Ms. memory^, num);{Sixth step: Save}Ms. SaveToFile (' C:\temp\test2.txt '); Ds. Free; Ms. Free; Fs. Free;End;End.
About Delphi Stream Usage (7) compression and decompression (Tcompressionstream, Tdecompressionstream)