对Zlib单元进行再封装

Posted hnxxcxg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对Zlib单元进行再封装相关的知识,希望对你有一定的参考价值。

对Zlib单元进行再封装

Zlib.pas是DELPHI自带的压缩单元,下面对对Zlib单元进行再封装,增加两个压缩函数,一个压缩流,一个压缩字符串:

unit Unit1;

interface

uses
  ZLib, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
  Forms, Dialogs;

type
  TForm1 = class(TForm)
  private
     Private declarations 
  public
     Public declarations 
  end;

var
  Form1: TForm1;
// 两个过程都有Compress参数,这个参数用来决定进行压缩操作还是解压操作: True--压缩; false--解压.
procedure Zip(Input, Output: TStream; Compress: Boolean); overload;

function Zip(Input: string; Compress: Boolean): string; overload;

implementation

$R *.dfm

procedure Zip(Input, Output: TStream; Compress: Boolean);
const
  MAXBUFSIZE = 1024 * 16; //16 KB
var
  CS: TCompressionStream;
  DS: TDecompressionStream;
  Buf: array[0..MAXBUFSIZE - 1] of Byte;
  BufSize: Integer;
begin
  if Assigned(Input) and Assigned(Output) then
  begin
    if Compress then     // 压缩
    begin
      CS := TCompressionStream.Create(ZLib.clDefault, Output);
      try
        CS.CopyFrom(Input, 0); //从开始处复制
      finally
        CS.Free;
      end;
    end
    else
    begin        // 解压
      DS := TDecompressionStream.Create(Input);
      try
        BufSize := DS.Read(Buf, MAXBUFSIZE);
        while BufSize > 0 do
        begin
          Output.Write(Buf, BufSize);
          BufSize := DS.Read(Buf, MAXBUFSIZE);
        end;
      finally
        DS.Free;
      end;
    end;
  end;
end;

function Zip(Input: string; Compress: Boolean): string;
var
  InputStream, OutputStream: TStringStream;
begin
  if Input = ‘‘ then
    Exit;
  InputStream := TStringStream.Create(Input);
  try
    OutputStream := TStringStream.Create(‘‘);
    try
      Zip(InputStream, OutputStream, Compress);
      Result := OutputStream.DataString;
    finally
      OutputStream.Free;
    end;
  finally
    InputStream.Free;
  end;
end;

end.

  

以上是关于对Zlib单元进行再封装的主要内容,如果未能解决你的问题,请参考以下文章

Qt之zip压缩/解压缩(QuaZIP)

如何对Linux虚拟机进行封装

python接口测试--unittest用例封装

phpexcel使用小记

虚拟机的封装

设计模式学习之策略模式