Ir al contenido


Foto

[TRUCO DELPHI] Comprimir y Descomprimir un Stream.


  • Por favor identifícate para responder
No hay respuestas en este tema

#1 sir.dev.a.lot

sir.dev.a.lot

    Advanced Member

  • Miembros
  • PipPipPip
  • 545 mensajes
  • Location127.0.0.1

Escrito 25 agosto 2016 - 11:23

[TRUCO DELPHI] Comprimir y Descomprimir un Stream.

 

Hay que adicionar esta Unidad.


delphi
  1. Uses ZLib;


delphi
  1. procedure CompressStream(inpStream, outStream: TStream);
  2. var
  3. InpBuf,OutBuf: Pointer;
  4. InpBytes,OutBytes: integer;
  5. begin
  6. InpBuf := nil;
  7. OutBuf := nil;
  8. try
  9. GetMem(InpBuf,inpStream.size);
  10. inpStream.Position := 0;
  11. InpBytes := inpStream.Read(InpBuf^,inpStream.size);
  12. CompressBuf(InpBuf,InpBytes,OutBuf,OutBytes);
  13. outStream.Write(OutBuf^,OutBytes);
  14. finally
  15. if InpBuf <> nil then FreeMem(InpBuf);
  16. if OutBuf <> nil then FreeMem(OutBuf);
  17. end;
  18. end;
  19.  
  20.  
  21.  
  22. procedure DecompressStream(inpStream, outStream: TStream);
  23. var
  24. InpBuf,OutBuf: Pointer;
  25. OutBytes,sz: integer;
  26. begin
  27. InpBuf := nil;
  28. OutBuf := nil;
  29. sz := inpStream.size-inpStream.Position;
  30. if sz > 0 then try
  31. GetMem(InpBuf,sz);
  32. inpStream.Read(InpBuf^,sz);
  33. DecompressBuf(InpBuf,sz,0,OutBuf,OutBytes);
  34. outStream.Write(OutBuf^,OutBytes);
  35. finally
  36. if InpBuf <> nil then FreeMem(InpBuf);
  37. if OutBuf <> nil then FreeMem(OutBuf);
  38. end;
  39. outStream.Position := 0;
  40. end;

Ejemplo de uso:


delphi
  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3. ms1, ms2 : TMemoryStream;
  4. begin
  5. ms1 := TMemoryStream.Create;
  6. try
  7. ms2 := TMemoryStream.Create;
  8. try
  9. RichEdit1.Lines.SaveToStream(ms1);
  10. CompressStream(ms1,ms2);
  11. ShowMessage(Format('Stream Compression Rate: %d %%',
  12. [round(100 / ms1.Size * ms2.Size)]));
  13. ms2.SaveToFile('C:\ms2.dat');
  14. finally
  15. ms1.Free;
  16. end;
  17. finally
  18. ms2.Free;
  19. end;
  20. end;
  21.  
  22.  
  23. procedure TForm1.Button2Click(Sender: TObject);
  24. var
  25. ms1, ms2 : TMemoryStream;
  26. begin
  27. ms1 := TMemoryStream.Create;
  28. try
  29. ms2 := TMemoryStream.Create;
  30. try
  31. ms1.LoadFromFile('C:\ms2.dat');
  32. DecompressStream(ms1,ms2);
  33. RichEdit1.Lines.LoadFromStream(ms2);
  34. finally
  35. ms1.Free;
  36. end;
  37. finally
  38. ms2.Free;
  39. end;
  40. end;

Saludos!


  • 2




IP.Board spam blocked by CleanTalk.