Delphi 5 提供了 Zlib 單元可以讓你在程式中內建壓縮資料的功能。 使用時需 Uses Zlib。 範例一:CompressBuf 及 DecompressBuf procedure TForm1.Button1Click(Sender: TObject); var i: integer; RawBuf: Pointer; ZipBuf: Pointer; RawBytes, ZipBytes: integer; s: string; p: PBYTE; begin RawBytes := 100; GetMem(RawBuf, RawBytes); GetMem(ZipBuf, RawBytes * 2); // 準備測試資料 p := RawBuf; for i := 0 to RawBytes-1 do begin p^ := (i div 8) mod 255; Inc(p); end; // 壓縮 CompressBuf(RawBuf, RawBytes, ZipBuf, ZipBytes); // 解壓縮 DecompressBuf(ZipBuf, ZipBytes, 100, RawBuf, RawBytes); // 把解壓縮後的資料以 Memo 元件顯示 s := ''; p := RawBuf; for i := 0 to RawBytes-1 do begin s := s + IntToStr(p^); Inc(p); end; Memo1.Lines.Add(s); FreeMem(RawBuf); FreeMem(ZipBuf); end; 範例二:以串流的方式壓縮/解壓縮工具函式 // Compress inpStream into outStream. procedure CompressStream(inpStream, outStream: TStream); var InpBuf,OutBuf: Pointer; InpBytes,OutBytes: integer; begin InpBuf := nil; OutBuf := nil; try GetMem(InpBuf, inpStream.Size); inpStream.Position := 0; InpBytes := inpStream.Read(InpBuf^, inpStream.Size); CompressBuf(InpBuf, InpBytes, OutBuf, OutBytes); outStream.Write(OutBuf^, OutBytes); finally if InpBuf <> nil then FreeMem(InpBuf); if OutBuf <> nil then FreeMem(OutBuf); end; end; (*-------------------------------------------------------- Decompress inpStream from it's current position If you want to decompress the whole inpStream, remember set inpStream.Position to 0 beforehand. --------------------------------------------------------*) procedure DecompressStream(inpStream, outStream: TStream); var InpBuf, OutBuf: Pointer; OutBytes, sz: integer; begin InpBuf := nil; OutBuf := nil; sz := inpStream.Size - inpStream.Position; if sz > 0 then try GetMem(InpBuf, sz); inpStream.Read(InpBuf^, sz); DecompressBuf(InpBuf, sz, 0, OutBuf, OutBytes); outStream.Write(OutBuf^, OutBytes); finally if InpBuf <> nil then FreeMem(InpBuf); if OutBuf <> nil then FreeMem(OutBuf); end; outStream.Position := 0; end;