//2.壓縮圖像
procedure CompressBitmap(var CompressedStream: TMemoryStream;const CompressionLevel: TCompressionLevel);
var
SourceStream: TCompressionStream;
DestStream: TMemoryStream;
Count: Integer;
Begin
//獲得圖像流的原始尺寸
Count := CompressedStream.Size;
DestStream := TMemoryStream.Create;
SourceStream:=TCompressionStream.Create
(CompressionLevel, DestStream);
Try
//SourceStream中保存著原始的圖像流
CompressedStream.SaveToStream(SourceStream);
//將原始圖像流進行壓縮, DestStream中保存著壓縮後的圖像流
SourceStream.Free;
CompressedStream.Clear;
//寫入原始圖像的尺寸
CompressedStream.WriteBuffer(Count, SizeOf
(Count));
//寫入經過壓縮的圖像流
CompressedStream.CopyFrom(DestStream, 0);
finally
DestStream.Free;
end;
end;
3.還原被壓縮圖像
procedure UnCompressBitmap(const CompressedStream: TFileStream; var Bmp: TBitmap);
var
SourceStream: TDecompressionStream;
DestStream: TMemoryStream;
Buffer: PChar;
Count: Integer;
Begin
//從被壓縮的圖像流中讀出原始圖像的尺寸
CompressedStream.ReadBuffer(Count, SizeOf(Count));
//根據圖像尺寸大小為將要讀入的原始圖像流分配內存塊
GetMem(Buffer, Count);
DestStream := TMemoryStream.Create;
SourceStream := TDecompressionStream.Create(CompressedStream);
Try
//將被壓縮的圖像流解壓縮,然後存入 Buffer內存塊中
SourceStream.ReadBuffer(Buffer^, Count);
//將原始圖像流保存至 DestStream流中
DestStream.WriteBuffer(Buffer^, Count);
DestStream.Position := 0;//復位流指針
//從 DestStream流中載入原始圖像流
Bmp.LoadFromStream(DestStream);
finally
FreeMem(Buffer);
DestStream.Free;
end;
end;