delphi 怎么把图片保存至数据库并读取

  • A+
所属分类:编程茶楼

procedure TForm1.LoadPictureClick(Sender: TObject);  // 上传图片
begin
  OpenPictureDialog1.Title := '打开图片';
  if OpenPictureDialog1.Execute then
  begin
    Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
  end;
end;

 

procedure TForm1.saveClick(Sender: TObject);   //保存
var
  Stream:TMemoryStream;
begin
  try
    Stream := TMemoryStream.Create; //  创建内存流
    Image1.Picture.Graphic.SaveToStream(Stream);   // 将图片保存到内存流中

   //Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);(另一种方法)
    adoquery1.Close;
    adoquery1.SQL.Clear;
    adoQuery1.SQL.Add('Insert into test3 values (:id,:photo)');
    ADOQuery1.Parameters.ParamByName('id').Value := editId.Text;
    adoQuery1.Parameters.ParamByName('photo').LoadFromStream(Stream,ftBlob); // 读取保存的内存图
    adoquery1.ExecSQL;
  finally
    Stream.Free;     // 释放内存流
  end;
end;

 

procedure TForm1.ReadClick(Sender: TObject);   // 读取图片
var
  Stream:TMemoryStream;
  Jpg:TjpegImage;
begin
  ADOQuery1.Close;
  ADOQuery1.SQL.Text:='SELECT * FROM test3 where id =' + editId.Text;   // 查询图片
  ADOQuery1.Open;
  if not ADOQuery1.FieldByName('photo').IsNull then
  begin
    Stream:=TMemoryStream.Create ;
    Jpg:=TjpegImage.Create ;
    TBlobField(ADOQuery1.FieldByName('photo')).SaveToStream(Stream);    // 显示的转换为BlobField并保存到内存流
    Stream.Position :=0;
    jpg.LoadFromStream(Stream);    // 加载图片
    image2.Picture.Assign(Jpg);
  end
  else
  begin
    image2.Picture :=nil;
  end;

    Stream.Free; 

    Jpg.Free;
end;

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: