最近在CSDN上看到兩篇關於《DELPHI中存取JPEG文件到SQLSERVER》中的文章之後,覺得其中講述的方法雖然有可取之處,但頗費時,我這裡有更簡單的操作方法,而且安全可靠,不敢一人獨享,願發布出來與大家共享。在Delphi7.0+Win2000+SqlServer 2000中測試通過,運行良好,現將思路、源碼公開如下:
解決思路:
1、 關鍵在於將打開的JPEG文件動態轉換為Tbitmap對象並顯示在Timage對象中;
2、 將顯示的圖片提交到數據庫中。
本例中在SQLSERVER2000中建立了一個試例表:exam(xm char(10),photo image);
程序源代碼:
unit SavePic;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtDlgs, ExtCtrls, DBCtrls, Grids, DBGrids, DB, ADODB, Buttons,
StdCtrls,Jpeg;
type
TForm1 = class(TForm)
SpeedButton1: TSpeedButton;
ADOConnection1: TADOConnection;
Table1: TADOTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
DBImage1: TDBImage;
Image1: TImage;
SpeedButton2: TSpeedButton;
OpenPictureDialog1: TOpenPictureDialog;
Label1: TLabel;
Label2: TLabel;
Edit1: TEdit;
SpeedButton3: TSpeedButton;
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.SpeedButton2Click(Sender: TObject);
var
bmp1:TBitmap;
jpg1:TJpegImage;
begin
OpenPictureDialog1.DefaultExt:=GraphicExtension(TJpegimage);
if OpenPictureDialog1.Execute then
begin
bmp1:=TBitmap.Create;
jpg1:=TJpegImage.Create;
try
jpg1.LoadFromFile(OpenPictureDialog1.FileName);
bmp1.Assign(jpg1);
Image1.Picture.Bitmap.Assign(bmp1);
finally
jpg1.Free;
bmp1.Free;
end;
end;
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
table1.Open;
table1.insert;
table1.fIEldbyname('xm').asstring:=Edit1.Text;
table1.FIEldByName('photo').Assign(Image1.Picture);
table1.post;
table1.Refresh;
end;
end.