Search code examples
delphidelphi-5

LoadFromStream doesn't appear to work in Delphi 5


I'm using Delphi 5 Enterprise because that's what the program I'm working with was written in. I have written a procedure which saves bitmaps to an Access database quite happily. Now I want to be able to retrieve the bitmaps. Saving the bitmaps, I use SaveToStream. Retrieving them, I used LoadFromStream but the compiler tells me that it doesn't recognise that function. The code is below:

 procedure TForm1.Button2Click(Sender: TObject);
 var
    Field : TBlobField;
    Stream : TStream;
    BMap : TBitMapImage;
 begin
   if BloBQuery.Active then
      begin
         Field := TBlobField(BlobQuery.FieldByName('Blob'));
         Stream := BlobQuery.CreateBlobStream(Field, bmRead);
         BMap := TBitMapImage.Create;
      try
         Image2.Picture.Graphic := BMap.LoadFromStream(Stream);
      finally
         BMap.Free;
         Stream.Free;
      end;
   end;
end;

Can anyone tell me when LoadFromStream won't work? It seems odd! Thanks.

The code which wrote the bitmap was:

    procedure TForm1.Button1Click(Sender: TObject);
var
  Field : TBlobField;
  Stream : TStream;
begin
   if (BlobQuery.Active = True) and (Image1.Picture.Graphic <> nil) then begin
       BlobQuery.Insert;
       Field := TBlobField(BlobQuery.FieldByName('Blob'));
       Stream := BlobQuery.CreateBlobStream(Field, bmWrite);
       try
          Image1.Picture.Graphic.SaveToStream(Stream);
       finally
          Stream.Free;
          BlobQuery.Post;
       end;
   end;
end;

Solution

  • Assuming Image1.Picture.Graphic was pointing at a TBitmap object when you saved it to the DB, you need to use a TBitmap object instead of a TBitMapImage object when reading the image back out, eg:

    procedure TForm1.Button2Click(Sender: TObject);
    var
      Field : TBlobField;
      Stream : TStream;
      BMap : TBitmap;
    begin
      if BlobQuery.Active then
      begin
        Field := TBlobField(BlobQuery.FieldByName('Blob'));
        Stream := BlobQuery.CreateBlobStream(Field, bmRead);
        try
          BMap := TBitmap.Create;
          try
            BMap.LoadFromStream(Stream);
            Image2.Picture.Graphic := BMap;
          finally
            BMap.Free;
          end;
        finally
          Stream.Free;
        end;
      end;
    end;
    

    Alternatively:

    procedure TForm1.Button2Click(Sender: TObject);
    var
      Field : TBlobField;
      Stream : TStream;
    begin
      if BlobQuery.Active then
      begin
        Field := TBlobField(BlobQuery.FieldByName('Blob'));
        Stream := BlobQuery.CreateBlobStream(Field, bmRead);
        try
          Image2.Picture.Bitmap.LoadFromStream(Stream);
        finally
          Stream.Free;
        end;
      end;
    end;