Delphi 对Zlib单元进行再封装


本文整理自网络,侵删。

 对Zlib单元进行再封装


低版本DELPHI,如D7,ZLIB.pas单元封装的很简陋,因此有必要再封装,以增加使用的便利性。

高版本DELPHI,zlib.pas本身提供的接口已经相当完善。

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

分别在D7和XE10.3.1下面,测试通过。

 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.

 

来源:https://www.cnblogs.com/hnxxcxg/p/11100238.html

相关阅读 >>

Delphi图片增加文字水印

Delphi 瞬间消除无用托盘图标(刷新托盘)

Delphi如何自动重启程序

Delphi将文件删除至回收站

Delphi环境下基于spcomm控件开发串口通讯报文字节丢失的问题解决

Delphi 中的颜色常量及效果图

Delphi tdictionary 简单用法

Delphi 安卓app的https访问权限

Delphi 循环 low high 用法

Delphi 取目录下指定文件到列表

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...