Mega Code Archive

 
Categories / Delphi / Examples
 

Read an image from a blob field in sql database

Question: I have received a SQL database that contains a table with a column named IMAGE which supposedly is a photo but I cannot display it by simply assigning a DBImage to that field. What should I do? Answer: You need to find out in what format the data is stored, e.g. it could be a JPEG file. Use the helper functions below to read the field and save it to a file. Then try loading those files with a image viewer. It's also a good idea to view the image with a hex editor (worst case: use Microsoft's DEBUG). If you're operating in a Microsoft environment :-) then it is possible that the images are stored as an OLE object. In this case there'll be an extra ~78 byte long header in the beginning to be skipped before the actual image file begins. Most image file formats have a signature that identify them e.g. JPEG files begin with 'JFIF'. GIF files begin with something like 'GIF89a' or 'GIF87..'. This information should help you determining if there's such an OLE header and how big it is. function BufferFromBlobField(var ABuffer; const ASize: integer; const ABlobField: TBlobField) : integer; var MemoryStream: TMemoryStream; begin { BufferFromBlobField } MemoryStream := TMemoryStream.Create; try ABlobField.SaveToStream(MemoryStream); MemoryStream.Seek(0, 0); Result := MemoryStream.Read(ABuffer, ASize) finally MemoryStream.Free end; { try } end; { BufferFromBlobField } function BlobFieldFromBuffer(const ABuffer; const ASize: integer; ABlobField: TBlobField) : integer; var MemoryStream: TMemoryStream; begin { BlobFieldFromBuffer } MemoryStream := TMemoryStream.Create; try Result := MemoryStream.Write(ABuffer, ASize); MemoryStream.Seek(0, 0); ABlobField.LoadFromStream(MemoryStream) finally MemoryStream.Free end; { try } end; { BlobFieldFromBuffer }