频道分类

Delphi 内存流和字符串相互转换

作者:admin 来源: 日期:2019/10/9 19:12:59 人气: 标签:

 unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, jpeg, ExtCtrls{, PSock};

type
  TForm1 = class(TForm)
    Image1: TImage;
    Button1: TButton;
    Image2: TImage;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  
function StreamToString(mStream:TStream): string;
{将内存流转换成字符串}
  function StringToStream(mString:string;mStream:TStream):Boolean;
{返回将字符串保存到内存流是否成功}

var
  Form1: TForm1;

implementation

{$R *.dfm}

function   StreamToString(mStream:   TStream):   string;
{将内存流转换成字符串}
var   
  I: Integer;
begin   
Result   :=   '';   
  if not Assigned(mStream) then Exit;
  SetLength(Result,   mStream.Size);
  for I := 0 to Pred(mStream.Size)do
  try
    mStream.Position   :=   I;
    mStream.Read(Result[Succ(I)],   1);
  except
    Result:='';
  end;
end;{StreamToString}

function   StringToStream(mString:   string;   mStream:   TStream):   Boolean;
{返回将字符串保存到内存流是否成功}
var   
  I: Integer;
begin   
Result:=True;
  try
    mStream.Size   :=   0;
    mStream.Position   :=   0;
    for I := 1 to Length(mString) do
    mStream.Write(mString[I],1);
  except
  Result   :=   False;
  end;
end;   {   StringToStream   }

procedure TForm1.Button1Click(Sender: TObject);
var
  Strm,Strn: TMemoryStream;
  Bitmap:TBitmap;
  vDir:String;
  tStr:String;
begin
  if Image1.Picture.Graphic <> nil then
  begin
    Strm:=TMemoryStream.Create;
    Strn:=TMemoryStream.Create;
    try
      Image1.Picture.Graphic.SaveToStream(Strm);

      tStr:=StreamToString(Strm); //TMenoryStream转化为字符串

      StringToStream(tStr,Strn); //字符串转化为TMenoryStream

      Strn.Position:=0;
      Bitmap:=TBitmap.Create;
      try
        Bitmap.LoadFromStream(Strn);
        Image2.Picture.Graphic:=Bitmap;
      finally
        Bitmap.Free;
      end;
    finally
      Strm.Free;
      Strn.Free;
    end;
  end;
end;

end.