近日笔者书写一个小型的学生管理系统时
需要用到ADO控件存取SQL Server数据库图片
查看资料发现基本都是针对BMP文件进行操作(巨增数据库大小)
但发现了eagletian高手翻译的ADO英文技术文档
里面涉及到了数据库存取JPEG文件的关键技术
在win
+sql server桌面版中测试通过
运行良好
现于源码公开如下
unit Unit;
interface
uses
Windows Messages SysUtils Classes Graphics Controls Forms Dialogs
ExtCtrls DBCtrls Grids DBGrids Db ADODBjpeg StdCtrlsdbtables;
{一定要USES JPEG单元使能存储JPG文件格式}
type
TForm = class(TForm)
DataSource: TDataSource;
ADOQuery: TADOQuery;
DBGrid: TDBGrid;
DBNavigator: TDBNavigator;
Image: TImage;
savebutton: TButton;
showbutton: TButton;
OpenDialog: TOpenDialog;
ADOQueryid: TIntegerField;
ADOQuerypic: TBlobField;
procedure savebuttonClick(Sender: TObject);
procedure showbuttonClick(Sender: TObject);
procedure DBNavigatorClick(Sender: TObject; Button: TNavigateBtn);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form: TForm;
implementation
{$R *DFM}
function JpegStartsInBlob(PicField:TBlobField):integer;
var
ghy: TADOBlobstream;
buffer:Word;
hx: string;
begin
Result := ;
ghy := TADOBlobstreamCreate(PicField bmRead);
try
while (Result = ) and (ghyPosition + < ghySize) do
begin
ghyReadBuffer(buffer );
hx:=IntToHex(buffer );
if hx = FF then begin
ghyReadBuffer(buffer );
hx:=IntToHex(buffer );
if hx = D then Result := ghyPosition
else if hx = FF then
ghyPosition := ghyPosition;
end; //if
end; //while
finally
ghyFree
end; //try
end;
procedure TFormsavebuttonClick(Sender: TObject);
var
picstream:tadoblobstream;
begin
adoqueryedit;
picstream:=tadoblobstreamCreate(tblobfield(adoqueryfields[])bmWrite);
if formopendialogexecute then
begin
picstreamLoadFromFile(opendialogfilename);
picstreamPosition:=;
adoqueryedit;
tblobfield(adoqueryFields[])loadfromstream(picstream);
adoquerypost;
end;
end;
procedure TFormshowbuttonClick(Sender: TObject);
var
ghy:TADOBlobstream;
pic:tjpegimage;
begin
ghy := TADOBlobstreamCreate(Adoquerypic bmRead);
try
ghySeek(JpegStartsInBlob(Adoquerypic)soFromBeginning);
Pic:=TJpegImageCreate;
try
PicLoadFromStream(ghy);
ImagePictureGraphic:=Pic;
finally
PicFree;
end;
finally
ghyFree
end;
end;
procedure TFormDBNavigatorClick(Sender: TObject; Button: TNavigateBtn);
begin
if button in [nbFirst nbPrior nbNext nbLast] then showbuttonClick;
end;
end
如果数据库中要存储的是BMP文件则在procedure TFormshowbuttonClick(Sender: TObject);过程中代码更改如下即可存储显示BMP文件格式的操作
procedure TFormshowbuttonClick(Sender: TObject);
var
ghy:TADOBlobstream;
pic:tbitmap;
begin
ghy := TADOBlobstreamCreate(Adoquerypic bmRead);
try
{ ghySeek(JpegStartsInBlob(Adoquerypic)soFromBeginning);}
Pic:=TbitmapCreate;
try
PicLoadFromStream(ghy);
ImagePictureGraphic:=Pic;
finally
PicFree;
end;
finally
ghyFree
end;
end;
到此用DELPHI存取JPEG文件到SQL Server数据库中的具体操作已经叙述完毕