看代码:
unit Unit2;
interface
uses Classes,SysUtils;
type
TBinStorage=class(TComponent)
private
FFilename,FOldFileName:String;
FBinStrm:TMemoryStream;
procedure WriteBin(Strm:TStream);
procedure ReadBin(Strm:TStream);
procedure SetFilename(const Value: String);
protected
procedure DefineProperties(Filer: TFiler);
override;
constructor Create(AOwner: TComponent);
override;
destructor Destroy;override;
published
property Filename:String read FFilename write SetFilename;
property BinStrm:TMemoryStream read FBinStrm ;
end;
procedure Register;
implementation
procedure Register;
begin
Classes.RegisterComponents('AAA',[TBinStorage]);
end;
{ TBinStorage }
constructor TBinStorage.Create(AOwner: TComponent);
begin
inherited;
BinStrm:=TMemoryStream.Create;
end;
procedure TBinStorage.DefineProperties(Filer: TFiler);
functiondo
Write:Boolean;
begin
Result:=(FFilename<>FOldFileName) and FileExists(FFilename);
end;
begin
inherited;
Filer.DefineBinaryProperty('BinStr',ReadBin,WriteBin,DoWrite);
end;
destructor TBinStorage.Destroy;
begin
BinStrm.Free;
inherited;
end;
procedure TBinStorage.ReadBin(Strm: TStream);
begin
BinStrm.LoadFromStream(strm);
end;
procedure TBinStorage.SetFilename(const Value: String);
begin
if FileExists(Value ) then
FFilename := Value
else
raise Exception.Create('File Not Exsit!');
end;
procedure TBinStorage.WriteBin(Strm: TStream);
var
f:TFileStream;
begin
FOldFileName:=FFilename;
f:=TFileStream.Create(FFilename,fmOpenRead);
try
Strm.CopyFrom(f,f.Size);
finally
f.Free ;
end;
end;
end.
在窗体上放这个控件。然后设置filename属性(就是你要存储的文件)
下面的代码把文件还原:
procedure TForm1.btn1Click(Sender: TObject);
var
F:TMemoryStream;
begin
F:=TMemoryStream.Create;
f.CopyFrom(bnstrg1.BinStrm,bnstrg1.BinStrm.Size);
f.SaveToFile('f:/1.pas');
f.Free;
end;
bnstrg1就是我的控件名称
先把图片用ZLib压缩,运行时从bnstrg1.BinStrm解压