如何在数据表中存取图片 - 回复 "三足乌" 的问题


问题来源: http://www.cnblogs.com/del/archive/2009/05/28/1491186.html#1801853

准备工作:
1、在空白窗体上添加: ClientDataSet1、Button1
2、激活窗体的 OnCreate 事件、激活 Button1 的 OnClick 事件

实现代码:


unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls, DB, DBClient;



type

  TForm1 = class(TForm)

    ClientDataSet1: TClientDataSet;

    Button1: TButton;

    procedure FormCreate(Sender: TObject);

    procedure Button1Click(Sender: TObject);

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



const

  PicPath1 = 'c:\temp\test1.bmp'; {保证测试图片的存在}

  PicPath2 = 'c:\temp\test2.bmp';



{建立数据表并载入数据}

procedure TForm1.FormCreate(Sender: TObject);

begin

  {建表}

  with ClientDataSet1 do begin

    FieldDefs.Add('Name', ftWideString, 8);

    FieldDefs.Add('Age', ftInteger);

    FieldDefs.Add('Picture', ftGraphic);

    CreateDataSet;

  end;



  {添加第一条数据}

  ClientDataSet1.Append;

  ClientDataSet1['Name'] := '张三';

  ClientDataSet1['Age']  := 66;

  TGraphicField(ClientDataSet1.FieldByName('Picture')).LoadFromFile(PicPath1);



  {添加第二条数据}

  ClientDataSet1.Append;

  ClientDataSet1['Name'] := '李四';

  ClientDataSet1['Age']  := 16;

  TGraphicField(ClientDataSet1.FieldByName('Picture')).LoadFromFile(PicPath2);

end;



{读出指定记录中的图片数据}

procedure TForm1.Button1Click(Sender: TObject);

var

  BlobStream: TClientBlobStream;

  GraphicField: TGraphicField;

  Bitmap: TBitmap;

begin

  {查找姓名是李四的记录}

  if ClientDataSet1.Locate('Name', '李四', []) then //可以把其中的李四换成张三试试

  begin

    {读取其 Picture 字段}

    GraphicField := ClientDataSet1.FieldByName('Picture') as TGraphicField;

    {读入到 Blob 流}

    BlobStream := TClientBlobStream.Create(GraphicField, bmRead);

    {给一个 TBitmap 流是为了看看}

    Bitmap := TBitmap.Create;

    Bitmap.LoadFromStream(BlobStream);

    Canvas.Draw(10, 10, Bitmap);

    Bitmap.Free;

    //

    BlobStream.Free;

  end;

end;



end.


 
   

你可能感兴趣的:(图片)