Loading a JPEG from DB

Hi.

I have been trying to load a JPEG image (blob) from an Access database into a TImage. Sometimes it works, sometimes not.

Now, how is the proper way of loading a blob Jpeg into a TImage?


I discovered that sometimes TImage.Picture.Assign(FieldByName('Image')); works, and sometimes TImage.Picture.Graphic.Assign(FieldByName('Image'));


Help.
LVL 1
sagerydAsked:
Who is Participating?
 
kretzschmarConnect With a Mentor Commented:
var
  m : tmemoryStream;
  jpg : TJpegImage;
begin
  m   := TMemoryStream.Create;
  jpg := TJpegImage.Create;
  try
    TBlobField(Dataset.FieldByName('FieldName')).SaveToStream(m);
    m.position := 0;
    jpg.LoadFormStream(m);
    image1.picture.bitmap.assign(jpg);
  finally
    m.free;
    jpg.free;
  end;
end;

meikl ;-)  
0
 
Stuart_JohnsonCommented:
I haven't tried it, but could you create a TBlobField, then stream-copy the contents of the field to a TJPEGImage?

I don't have access here, but I'm sure there must be an easy way of doing it.  I'll try it later when I'm infront of a PC with Access on it.

Stu
0
 
mocartsCommented:
from my PAQ (http://www.experts-exchange.com/Programming/Programming_Languages/Delphi/Q_20532935.html)


uses jpeg;

procedure TForm1.btnSaveClick(Sender: TObject);
begin
 Query1.SQL.Text := 'INSERT INTO htest (img) values (:img)';
 Query1.ParamByName('img').LoadFromFile('D:\My.jpg', ftGraphic);
 Query1.ExecSQL;
end;

procedure TForm1.btnLoadClick(Sender: TObject);
var
s: TStream;
buf: word;
gf: TGraphic;
begin
Query1.SQL.Text := 'SELECT img FROM htest';
Query1.Open;
Query1.First;
s := Query1.CreateBlobStream(Query1.FieldByName('img'), bmRead);
try
  if s.read(buf, sizeof(buf)) <> sizeOf(buf) then exit;
  s.Position := 0;
  if buf = $D8FF then
    gf := TJPEGImage.Create
  else if buf = $4D42 then
    gf := TBitmap.Create
  else if buf = $CDD7 then
    gf := TMetafile.Create
  else if buf = 0 then  
    gf := TIcon.Create;
  try
    gf.LoadFromStream(s);
    Image1.Picture.Graphic := gf;
  finally
    gf.Free;
  end;
finally
  s.Free;  // must free stream
end;
end;
0
 
sagerydAuthor Commented:
Cool because I just solved it myself with pretty much the exact same code. Thanks for the confirmation :)

Mocarts, looks like a good solution, but since I'm only using jpegs your code is overkill. Thanks anyway.


johan
0
 
mocartsCommented:
of course, if you use only jpeg then you can ommit those if's structures.
only what I wanted show you is how to skip intermediate stream usage by using TDataSet's CreateBlobStream.

wbr, mo.
0
All Courses

From novice to tech pro — start learning today.