Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an arbitrary image from a BLOB stream into a TImage?

If I understand it correctly, TImage.LoadFromFile determines the type of picture from the file extension.

Is there any way to detect the image type automatically from a TBlobStream with a raw image in it?

My current code:

procedure LoadImageFromStream(AImage: TImage; ADataSet: TDataSet);
var
  Stream: TStream;
begin
  Stream := ADataSet.CreateBlobStream(Field, bmRead);
  try
    AImage.Picture.Graphic.LoadFromStream(Stream);
  finally
    Stream.Free;
  end;
end
like image 211
Jens Mühlenhoff Avatar asked Jun 06 '11 11:06

Jens Mühlenhoff


3 Answers

See this SO answer for file content retrieval from header.

Or you can use our TSynPicture class, which will handle all kind of pictures (bmp/gif/tiff/jpg/png) using Gdi+ library, in one single class. So your TPicture can be this unique class, for any kind of picture. With less code overhead than the Jpeg or PNG Delphi units.

var Pic: TSynPicture;

Pic := TSynPicture.Create;
Pic.LoadFromStream(aStream); // will load bmp/gif/tiff/jpeg/png content
AImage.Picture.Graphic := Pic;
....
like image 156
Arnaud Bouchez Avatar answered Nov 19 '22 08:11

Arnaud Bouchez


starting from here you can easily do it: http://delphihaven.wordpress.com/2011/01/22/tip-detecting-graphic-formats/

like image 7
RBA Avatar answered Nov 19 '22 07:11

RBA


In fact it is TPicture.LoadFromFile that detects file type, and it just uses the file extension. So you'll need to read the header of the stream to detect the file type.

On the other hand, if you know what the format is when you put the BLOB into the database you could always include that information as your own private header to the BLOB.

like image 2
David Heffernan Avatar answered Nov 19 '22 08:11

David Heffernan