熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Delphi編程 >> 正文

DELPHI存取JPEG文件到SQL Server數據庫

2022-06-13   來源: Delphi編程 
 近日筆者書寫一個小型的學生管理系統時需要用到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數據庫中的具體操作已經敘述完畢


From:http://tw.wingwit.com/Article/program/Delphi/201311/24961.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.