备注:adoconnection1.connectstring := 'Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=demo;Data Source=Mysqlserver'Mysqlserver为SQL服务器的名称请据实际情况更改。三、 程序代码(首先在单元文件接口部分的uses语句中添入JPEG单元引用)
1. 图像数据的选择及保存
procedure TForm1.selectimageClick(Sender: TObject); //选择图像beginif openpicturedialog1.Execute thenimage1.Picture.LoadFromFile(openpicturedialog1.FileName );end;
procedure TForm1.savetodbClick(Sender: TObject); //保存图像varstrm:tmemorystream; ext:string;beginif image1.picture.Graphic <> nil then //避免image1中无图像保存出错beginext:=extractfileext(openpicturedialog1.FileName ); //取出文件的扩展名strm := tmemorystream.Create ;tryimage1.Picture.Graphic.SaveToStream(strm);adotable1.Edit ;strm.Position :=0; tblobfield(adotable1.FieldByName('myimage')).LoadFromStream(strm);//如需直接由文件保存可采用如下注释行//TBlobField(adotable1.FieldByName('myimage')).LoadFromFile(OpenPictureDialog1.FileName);//以下记录保存到数据库的图像格式if uppercase(ext) = '.BMP' thenadotable1.FieldByName('isbmp').Value := 1 //BMP型图像数据else if (uppercase(ext) = '.JPG') OR ( uppercase(ext) = '.JPEG') Thenadotable1.FieldByName('isbmp').Value := 0; //JPEG型图像数据adotable1.Post ;finallystrm.Free ; //笔者发现如strm采用tblobstream类,程序运行到该语句会出现问题end;end;end;
2. 图像数据的读取及显示 从数据库图像字段中读取数据然后在Image1中把图像显示出来的程序代码,笔者先尝试在Datasource1的OnDataChange事件中来完成,但会出错,后改写在adotable1的afterscroll事件中顺利完成。
procedure TForm1.adoTable1AfterScroll(DataSet: TDataSet); //显示图像varstrm:tadoblobstream;jpegimage:tjpegimage;bitmap:tbitmap;beginstrm := tadoblobstream.Create(tblobfield(adotable1.fieldbyname('MYIMAGE')),bmread);try //try1strm.position :=0;image1.Picture.Graphic := nil; //清除图像// BMP、JPEG两种图像数据必需分别处理if adotable1.fieldbyname('isbmp').asstring ='1' then //BMP型图像数据begin //begin11bitmap := tbitmap.Create ;try //try11bitmap.LoadFromStream(strm);image1.Picture.Graphic := bitmap;finallybitmap.Free;end; //end try11end //end begin11else if adotable1.fieldbyname('isbmp').asstring ='0' then //JPEG型图像数据begin //begin12jpegimage := tjpegimage.Create ;try //try12jpegimage.LoadFromStream(strm);image1.Picture.Graphic := jpegimage;finallyjpegimage.Free ;end; //end try12end; //end begin12finallystrm.Free ;end; //end try1end;
如果你想将数据库中的图像导出到外部文件中可采用如下关键语句:
image1.Picture.SaveToFile(FileName );
以上程序代码不但适用于SQL数据库,而且完全适用于ACCESS数据库,但创建ACCESS数据库时应注意图像字段的数据类型应为OLE型,数据库创建完成之后再将Adoconnection1连接到该ACCESS数据库即可运行。欲知详细情况,请索取源程序。以上提供了DELPHI利用Tsteam类存取JPEG、BMP图像到数据库的一种解决方案,笔者争取下文介绍DELPHI利用ASSIGN方法存取JPEG、BMP图像到数据库的另一解决方案。 以上程序代码在DELPHI6.0+SQL(或ACCESS)数据库下运行通过。