将JPEG保存到数据库

时间:2014-06-16 23:59:22

标签: delphi

此代码在TBlobField行提供访问冲突:

procedure TfrmCapture.Button3Click(Sender: TObject);
var
  j: TJPEGImage;
  S: TFileStream;
begin
  J := TJPEGImage.Create;
  try
    J.Assign(Image1.Picture.Graphic);
    J.CompressionQuality := 80;
    J.Compress;
    J.SaveToStream(S);
    S.Position := 0;
    TBlobField(frmSignout.tblImg.FieldByName('Picture')).LoadFromStream(S);
  finally
    J.Free;
  end;
  Image1.Picture := nil;
  Close;
end;

基本上我试图将Timage转换为JPEG然后将其保存到Image字段(MSSQL express) 任何想法如何解决它?

2 个答案:

答案 0 :(得分:5)

您没有实例化保存到的TFileStream

procedure TfrmCapture.Button3Click(Sender: TObject);
var
 J: TJPEGImage;
 S: TFileStream;
begin
  J := TJPEGImage.Create;
  try
    J.Assign(Image1.Picture.Graphic);
    J.CompressionQuality := 80;
    J.Compress;
    S := TFileStream.Create('c:\path to\somefile.jpg', fmCreate); // <-- add this!
    try
      J.SaveToStream(S);
      S.Position := 0;
      TBlobField(frmSignout.tblImg.FieldByName('Picture')).LoadFromStream(S);
    finally
      S.Free; // <-- add this
    end;
  finally
    J.Free;
  end;
  Image1.Picture := nil;
  Close;
end;

话虽如此,我建议完全避免使用该文件(除非您真的需要它)并使用TDataSet.CreateBlobStream()代替TBlobField.LoadFromStream()

procedure TfrmCapture.Button3Click(Sender: TObject);
var
 J: TJPEGImage;
 S: TStream;
begin
  J := TJPEGImage.Create;
  try
    J.Assign(Image1.Picture.Graphic);
    J.CompressionQuality := 80;
    J.Compress;
    S := frmSignout.tlbImg.CreateBlobStream(frmSignout.tblImg.FieldByName('Picture'), bmWrite); 
    try
      J.SaveToStream(S);
    finally
      S.Free;
    end;
  finally
    J.Free;
  end;
  Image1.Picture := nil;
  Close;
end;

答案 1 :(得分:0)

Man我只是累了...当然它不是文件流的内存流..jeez。

这是在MSSQL express中保存Timage为JPEG的正确代码(~50kb / image):

procedure TfrmCapture.Button3Click(Sender: TObject);
var
j:TJPEGImage;
S : TMemorystream;
begin
J := TJPEGImage.Create;
S := Tmemorystream.Create;
try
J.Assign(image1.Picture.graphic);
J.CompressionQuality :=80;
J.Compress;
J.SaveToStream(S);
S.Position :=0;
(frmSignout.tblImg.FieldByName('Picture') as TblobField).LoadFromStream(S);
finally
J.Free;
S.Free;
end;
image1.Picture :=nil;
close;
end;