unit ZSCompF;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, EditBtn, ZStream;

type

  { TForm1 }

  TForm1 = class(TForm)
    btnComprimir: TButton;
    btnDescomprimir: TButton;
    edOrigen: TFileNameEdit;
    Memo1: TMemo;
    lblOrigen: TLabel;
    lblDestino: TLabel;
    edCompressed: TEdit;
    procedure btnComprimirClick(Sender: TObject);
    procedure btnDescomprimirClick(Sender: TObject);
    procedure edOrigenAcceptFileName(Sender: TObject; var Value: String);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation


{$R *.lfm}

function ComprimirFlujo (aOrigen, aDestino: TStream): Single;
var
  compFlujo: TCompressionStream;
begin
  compFlujo := TCompressionStream.Create(
    clFastest, aDestino);
  try
    compFlujo.CopyFrom(aOrigen, aOrigen.Size);
    //Porcentaje de compresión
    Result := compFlujo.get_CompressionRate;
  finally
    compFlujo.Free;
  end;
end;


procedure DescomprimirFlujo (aOrigen, aDestino: TStream) ;
var
  decompFlujo: TDecompressionStream;
  Lectura: Integer;
  Buffer: array [0..1023] of Char;
begin
  decompFlujo := TDecompressionStream.Create(aOrigen);
  try
     {aFlujoDest.CopyFrom (decompFlujo, tamano) no funciona
     porque no se sabe cuánto vale tamano}
    repeat
      Lectura := decompFlujo.Read(Buffer, 1024);
      aDestino.Write (Buffer, Lectura);
    until Lectura = 0;
  finally
    decompFlujo.Free;
  end;
end;

procedure TForm1.btnComprimirClick(Sender: TObject);
var
  aOrigenFlujo, aDestinoFlujo: TFileStream;
begin
  aOrigenFlujo := TFileStream.Create (edOrigen.Text, fmOpenRead);
  aDestinoFlujo := TFileStream.Create (edCompressed.Text, fmCreate);
  try
    ComprimirFlujo (aOrigenFlujo, aDestinoFlujo);
    aDestinoFlujo.Position := 0;
    Memo1.Lines.LoadFromStream (aDestinoFlujo);

  finally
    aOrigenFlujo.Free;
    aDestinoFlujo.Free;
  end;
end;

procedure TForm1.btnDescomprimirClick(Sender: TObject);
var
  aFlujoOrigen: TFileStream;
  aFlujoDestino: TMemoryStream;
begin
  aFlujoOrigen := TFileStream.Create (edCompressed.Text, fmOpenRead);
  aFlujoDestino := TMemoryStream.Create;
  try
    DescomprimirFlujo(aFlujoOrigen, aFlujoDestino);
    aFlujoDestino.Position := 0;
    Memo1.Lines.LoadFromStream(aFlujoDestino);
  finally
    aFlujoOrigen.Free;
    aFlujoDestino.Free;
  end;
end;

procedure TForm1.edOrigenAcceptFileName(Sender: TObject; var Value: String);
begin
  edOrigen.Text := ExtractFilePath(Value)+ ExtractFileName(Value);
  edCompressed.Text := edOrigen.Text + '.zsc';
end;


end.


