流的压缩和解压

(*//
标题:流的压缩和解压
说明:适用文件压缩、图象压缩等;调用ZLib单元的方法实现
设计:Zswang
支持:wjhu111@21cn.com
日期:2004-03-24
//*)

(*//============================================================================
设计思路:
创建TCompressionStream、TDecompressionStream实例进行压缩和解压
============================================================================//*)

uses ZLib;

const cBufferSize = $4096;

function StreamCompression(mInputStream: TStream; mOutputStream: TStream): Integer;
var
  I: Integer;
  vBuffer: array[0..cBufferSize]of Char;
begin
  Result := -1;
  if not (Assigned(mInputStream) and Assigned(mOutputStream)) then Exit;
  with TCompressionStream.Create(clMax, mOutputStream) do try
    for I := 1 to mInputStream.Size div cBufferSize do begin
      mInputStream.Read(vBuffer, cBufferSize);
      Write(vBuffer, cBufferSize);
    end;
    I := mInputStream.Size mod cBufferSize;
    if I > 0 then begin
      mInputStream.Read(vBuffer, I);
      Write(vBuffer, I);
    end;
  finally
    Free;
  end;
end; { StreamCompression }

function StreamDecompression(mInputStream: TStream; mOutputStream: TStream): Integer;
var
  vBuffer: array[0..cBufferSize]of Char;
  I: Integer;
begin
  Result := -1;
  if not (Assigned(mInputStream) and Assigned(mOutputStream)) then Exit;
  with TDecompressionStream.Create(mInputStream) do try
    repeat
      I := Read(vBuffer, cBufferSize);
      mOutputStream.Write(vBuffer, I);
    until I = 0;
    Result := mOutputStream.Size;
  finally
    Free;
  end;
end; { StreamDecompression }

//Example
procedure TForm1.Button1Click(Sender: TObject);
var
  vInputStream: TFileStream;
  vOutputStream: TFileStream;
begin
  vInputStream := TFileStream.Create('c:/temp/temp.exe', fmOpenRead);
  vOutputStream := TFileStream.Create('c:/temp/temp.exe.z', fmCreate);
  try
    StreamCompression(vInputStream, vOutputStream);
  finally
    vInputStream.Free;
    vOutputStream.Free;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  vInputStream: TFileStream;
  vOutputStream: TFileStream;
begin
  vInputStream := TFileStream.Create('c:/temp/temp.exe.z', fmOpenRead);
  vOutputStream := TFileStream.Create('c:/temp/temp~.exe', fmCreate);
  try
    StreamDecompression(vInputStream, vOutputStream);
  finally
    vInputStream.Free;
    vOutputStream.Free;
  end;
end;
  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

zswangII

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值