如何壓縮memoryStream |
答題得分者是:kaida
|
will
中階會員 發表:176 回覆:135 積分:62 註冊:2002-04-14 發送簡訊給我 |
|
00156
高階會員 發表:45 回覆:195 積分:112 註冊:2002-06-01 發送簡訊給我 |
|
kaida
中階會員 發表:4 回覆:35 積分:52 註冊:2003-03-02 發送簡訊給我 |
uses
ZLib; { 壓縮 Stream }
procedure CompressStream(inpStream, outStream: TMemoryStream);
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; { 解壓縮 stream }
procedure DecompressStream(inpStream, outStream: TMemoryStream);
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; {
示例:
壓縮 RichEdit1 的內容並且計算壓縮率,然後保存壓縮後的 stream。
} procedure TForm1.Button1Click(Sender: TObject);
var
ms1, ms2: TMemoryStream;
begin
ms1 := TMemoryStream.Create;
try
ms2 := TMemoryStream.Create;
try
RichEdit1.Lines.SaveToStream(ms1);
CompressStream(ms1, ms2);
ShowMessage(Format('壓縮率: %d %%',[round(100 / ms1.Size * ms2.Size)]));
ms2.SaveToFile('C:\test.dat');
finally
ms1.Free;
end;
finally
ms2.Free;
end;
end; {
載入文件流並解壓縮,然後寫入 RichEdit1。
} procedure TForm1.Button2Click(Sender: TObject);
var
ms1, ms2: TMemoryStream;
begin
ms1 := TMemoryStream.Create;
try
ms2 := TMemoryStream.Create;
try
ms1.LoadFromFile('C:\test.dat');
DecompressStream(ms1, ms2);
RichEdit1.Lines.LoadFromStream(ms2);
finally
ms1.Free;
end;
finally
ms2.Free;
end;
end;
|
will
中階會員 發表:176 回覆:135 積分:62 註冊:2002-04-14 發送簡訊給我 |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |