Delphi data compression processing (2)
Buffer: PChar;
Count: Integer;
Begin
file://Read the original image size from the compressed image stream
ComPRessedStream.ReadBuffer(Count, SizeOf(Count));
file://Allocate memory blocks for the original image stream to be read based on the image size
GetMem(Buffer, Count);
DestStream := TMemoryStream.Create;
SourceStream := TDecompressionStream.Create(CompressedStream);
Try
file://decompresses the compressed image stream and stores it in the Buffer memory block
SourceStream.ReadBuffer(Buffer^, Count);
file://save the original image stream to the DestStream stream
DestStream.WriteBuffer(Buffer^, Count);
DestStream.Position := 0;//Reset stream pointer
//Load the original image stream from the DestStream stream
Bmp.LoadFromStream(DestStream);
finally
FreeMem(Buffer);
DestStream.Free;
end;
end;
4. Compression button OnClick event
procedure TForm1.Button1Click(Sender: TObject);
var
Bmp: TBitmap;
CompressedStream: TMemoryStream;
begin
Bmp := TBitmap.Create;
CompressedStream := TMemoryStream.Create;
Try
file://Capture the entire current screen and save the image to the Bmp object GetScreen(Bmp);
file:// saves the image in the Bmp object to the memory stream
Bmp.SaveToStream(CompressedStream);
file://Compresses the original image stream according to the default compression ratio
CompressBitmap(CompressedStream, clDefault);
file://Save the compressed image stream as a file in a custom format
CompressedStream.SaveToFile(' C:cj.dat' );
finally
Bmp.Free;
CompressedStream.Free;
end;
end;
5. Unzip button OnClick event
procedure TForm1.Button2Click(Sender: TObject);
var
CompressedStream: TFileStream;
Bmp: TBitmap;
begin
Bmp := TBitmap.Create;
file://opens a custom compressed format file in read-only mode of the file stream
CompressedStream := TFileStream.Create(' C:cj.dat' , fmOpenRead);
Try
file://decompresses the compressed image stream
UnCompressBitmap(CompressedStream, Bmp);
file://Restore the original image stream to the specified BMP file
Bmp.SaveToFile(' C:cj.bmp' );
finally
Bmp.Free;
CompressedStream.Free;
end;
end;
In addition, the TCompressionStream object also provides the CompressionRate property, which is used to describe the compression ratio after compressing the original data. The OnProgress event is triggered during the compression and decompression processes. Developers can write in this event to display the progress. code.
The above code passes debugging and running in Delphi 5.0.