既能识别bmp又识别读jpeg,我把代码修改如下:
(建议用image,不要用dbimage控件,因为该控件只能识别bmp格式图片)
(程序已调试,运行正确 delphi7 + sql server 2000)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Grids, DBGrids, DB, ADODB, StdCtrls, DBCtrls;
type
TForm1 = class(TForm)
DataSource1: TDataSource;
ADOQuery1: TADOQuery;
DBGrid1: TDBGrid;
OpenDialog1: TOpenDialog;
Button1: TButton;
Button2: TButton;
DBImage1: TDBImage;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses DateUtils,jpeg;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
with ADOQuery1 do
begin
close;
SQL.Text:= 'select * from Tpic';
ADOQuery1.Open;
end;
//DBImage1.DataSource:= DataSource1;
//DBImage1.DataField:= 'pic';
end;
//显示
procedure TForm1.Button1Click(Sender: TObject);
var
aBitmap: TBitmap;
aJPEGImage: TJPEGImage;
aStream: TStream;
head: word;
const
bmp = $4D42;
jpeg = $D8FF;
begin
aBitmap:= TBitmap.Create;
aJPEGImage:= TJPEGImage.Create;
aStream:= TMemoryStream.Create;
try
TBlobField(ADOQuery1.FieldByName('pic')).SaveToStream(aStream);
aStream.Position := 0; //一定要有这句
aStream.Read(head,2);
aStream.Position:= 0;
if head = bmp then
begin
aBitmap.LoadFromStream(aStream);
Image1.Picture.Assign(aBitmap);
end
else if head = jpeg then
begin
aJPEGImage.LoadFromStream(aStream);
Image1.Picture.Assign(aJPEGImage);
end;
finally
aBitmap.Free;
aJPEGImage.Free;
aStream.Free;
end;
end;
//添加
procedure TForm1.Button2Click(Sender: TObject);
var
aBitmap: TBitmap;
aJPEGImage: TJPEGImage;
aStream: TStream;
begin
aBitmap:= TBitmap.Create;
aJPEGImage:= TJPEGImage.Create;
aStream:= TMemoryStream.Create;
try
if OpenDialog1.Execute then
begin
if ExtractFileExt(OpenDialog1.FileName)= '.bmp'then
begin
aBitmap.LoadFromFile(OpenDialog1.FileName);
aBitmap.SaveToStream(aStream);
end
else if (ExtractFileExt(OpenDialog1.FileName)= '.jpg') or (ExtractFileExt(OpenDialog1.FileName)= '.jpeg') then
begin
aJPEGImage.LoadFromFile(OpenDialog1.FileName);;
aJPEGImage.SaveToStream(aStream);
end;
with ADOQuery1 do
begin
Append;
aStream.Position:= 0;
TBlobField(FieldByName('pic')).LoadFromStream(aStream);//出错的地方:原来是因为我用了dbimage控件,该控件只能显示bmp格式图片
Post;
end;
end;
finally
aBitmap.Free;
aJPEGImage.Free;;
aStream.Free;
end;
end;
end.