Search code examples
sqlitedelphibitmapblobfiremonkey

Delphi - How to save bitmap to BLOB field in SQLite database


I am trying to add an array of TBitmap images to different records of a ClientDataSet (in a ftBlob field) and then save those records to a SQLite database. The BLOB field (DocImage) is a required field in the database.

However, my code does not seem to save the bitmaps to the blob field in the ClientDataSet at all... So when I call BdmMain.cdsTrxDoc.ApplyUpdates(0), I get the error: "Field 'DocImage' must have a value."

I have checked the size of my BlobStream (BlobStream.Size) before and after calling FTrxPhotoValue[i].SaveToStream(BlobStream) and it does increase in size, but BlobField's data size remains 0.

Here is a snippet of the code:

FTrxIDValue: Integer;
FTrxDocIDValue: array of Integer;
FTrxPhotoValue: array of TBitmap;
// ...
for i := 0 to Length(FTrxPhotoValue) do
begin
  BdmMain.cdsTrxDoc.Insert;
  BdmMain.cdsTrxDoc['TrxID'] := FTrxIDValue;
  BdmMain.cdsTrxDoc['DocID'] := FTrxDocIDValue[i];
  BlobField := BdmMain.cdsTrxDoc.FieldByName('DocImage');
  BlobStream := BdmMain.cdsTrxDoc.CreateBlobStream(BlobField, bmWrite);
  FTrxPhotoValue[i].SaveToStream(BlobStream);
end;
// ...
BdmMain.cdsTrxDoc.ApplyUpdates(0);

Solution

  • You should Free the stream after the call to SaveToStream. The stream will update the underlying field only during Destroy.