╃ DATA的天空 ╃

                                      -=technology=-

                                                                                DATA vs LONA   天下无双  ^_^                             

 |  |


Delphi存取图像解决方案

=====data发表于技术|11:25:0

1. 图像数据的选择及保存

procedure TForm1.selectimageClick(Sender: TObject); //选择图像
begin
if openpicturedialog1.Execute then
image1.Picture.LoadFromFile(openpicturedialog1.FileName );
end;

procedure TForm1.savetodbClick(Sender: TObject); //保存图像
var
strm:tmemorystream;
ext:string;
begin
if image1.picture.Graphic <> nil then //避免image1中无图像保存出错
begin
ext:=extractfileext(openpicturedialog1.FileName ); //取出文件的扩展名
strm := tmemorystream.Create ;
try
image1.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' then
adotable1.FieldByName('isbmp').value := 1 //BMP型图像数据
else if (uppercase(ext) = '.JPG') OR ( uppercase(ext) = '.JPEG') Then
adotable1.FieldByName('isbmp').value := 0; //JPEG型图像数据
adotable1.Post ;
finally
strm.Free ; //笔者发现如strm采用tblobstream类,程序运行到该语句会出现问题
end;
end;
end;

2. 图像数据的读取及显示

从数据库图像字段中读取数据然后在Image1中把图像显示出来的程序代码,笔者先尝试在Datasource1的OnDataChange事件中来完成,但会出错,后改写在adotable1的afterscroll事件中顺利完成。


procedure TForm1.adoTable1AfterScroll(DataSet: TDataSet); //显示图像
var
strm:tadoblobstream;
jpegimage:tjpegimage;
bitmap:tbitmap;
begin
strm := tadoblobstream.Create(tblobfield(adotable1.fieldbyname('MYIMAGE')),bmread);
try //try1
strm.position :=0;
image1.Picture.Graphic := nil; //清除图像
// BMP、JPEG两种图像数据必需分别处理
if adotable1.fieldbyname('isbmp').asstring ='1' then //BMP型图像数据
begin //begin11
bitmap := tbitmap.Create ;
try //try11
bitmap.LoadFromStream(strm);
image1.Picture.Graphic := bitmap;
finally
bitmap.Free;
end; //end try11
end //end begin11
else if adotable1.fieldbyname('isbmp').asstring ='0' then //JPEG型图像数据
begin //begin12
jpegimage := tjpegimage.Create ;
try //try12
jpegimage.LoadFromStream(strm);
image1.Picture.Graphic := jpegimage;
finally
jpegimage.Free ;
end; //end try12
end; //end begin12
finally
strm.Free ;
end; //end try1
end;

如果你想将数据库中的图像导出到外部文件中可采用如下关键语句:


image1.Picture.SaveToFile(FileName );

  以上程序代码不但适用于SQL数据库,而且完全适用于ACCESS数据库,但创建ACCESS数据库时应注意图像字段的数据类型应为OLE型,数据库创建完成之后再将Adoconnection1连接到该ACCESS数据库即可运行。欲知详细情况,请索取源程序。以上提供了DELPHI利用Tsteam类存取JPEG、BMP图像到数据库的一种解决方案,笔者争取下文介绍DELPHI利用ASSIGN方法存取JPEG、BMP图像到数据库的另一解决方案。

  以上程序代码在DELPHI6.0+SQL(或ACCESS)数据库下运行通过



{CommentAuthor}【评 论】 -----{CommentTime}

{CommentEmail} {CommentUrl} {CommentIp}

{CommentContent}

流逝的时光

最 新 评 论

友 情 链 接

搜 索

DATA 最新的 20 条日志

 


2004 Copyright by {lionellai}  Powered by {5DBlog.com}