SQL Server 2005里的Image字段装的就是文本类型数据;
delphi上传图片--个人照片
1. 使用到的控件:
(1) Image 控件(TImage类的);
(2) OpenPictureDialog控件(打开图片的控件);
2. 使用到一个类:TMemoryStream
3. 数据库的字段:Blob字段;存放图像的二进制;
功能一: 清除照片
步骤:
Image1.Picture.Graphic := nil ;
Image1.Tag := 1 ;
使用如下语句即可;
功能二: 添加照片
步骤:
1. 打开硬盘,选择照片时,用以下过程:
procedure TRYGLEditForm.image1DblClick(Sender: TObject);
var
filestream:TFileStream;
begin
inherited;
if not (dsMaster.State in [dsEdit , dsInsert]) then
exit ;
if dlgOpenPic1.Execute then
begin
try
filestream := TFileStream.Create(dlgOpenPic1.FileName,fmOpenRead);
if filestream.Size > 20000 then
begin
MsgDialog.ShowError('图片太大影响速度,不能超过20K大小');
abort;
end;
finally
filestream.free;
end;
Image1.Picture.LoadFromFile(dlgOpenPic1.FileName);
Image1.Tag := 1 ;
end;
end;
2. 保存到数据库时:
{--cyj 保存图片--}
procedure TRYGLEditForm.SavePicture;
var
PicName , ext : string ;
strm : TMemoryStream;
begin
try
if Image1.Picture.Graphic = nil then exit;
strm := TMemoryStream.Create ;
Image1.Picture.Graphic.SaveToStream(Strm);
strm.Position := 0 ;
if strm.Size = 0 then
cdsPHOTO.FieldByName('photo').Clear
else
begin
With cdsPHOTO do
begin
if recordcount > 0 then
Edit
else
Append;
TBlobField(FieldByName('PHOTO')).LoadFromStream(strm);
Post;
ApplyUpdates;
end;
end;
finally
strm.Free ;
end;
end ;
//--读取图片到Image控件, 在formshow事件里调用ShowPhoto()即可
{--显示个人照片 支持bmp jpg格式--}
procedure TFmEmployeeInput.ShowPhoto();
var
//strm: TADOBlobStream;
strm: TClientBlobStream; //--因为用的是ClientDataSet组件作为数据读取控件
JpegImage: TJpegImage;
Bitmap: TBitmap;
PType: Integer;
begin
PType := 0;
if FMEmployee.CDS1.FieldByName('photo').AsString = '' then
begin
Exit;
end;
strm := TClientBlobStream.Create(tblobfield(FMEmployee.CDS1.FieldByName('photo')),bmread);
try //try1
strm.position :=0;
image1.Picture.Graphic := nil; //清除图像
// BMP、JPEG两种图像数据必需分别处理
if PType = 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 PType = 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;