对Zlib单元进行再封装

对Zlib单元进行再封装

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

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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.

  

posted @   delphi中间件  阅读(745)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示