JPG and PNG inside a database (VCL)

In VCL applications we can easily add images to a database using the TDBImage component. But TDBImage only supports Bitmaps (BMP), and these uncompressed images take a lot of space and network bandwidth to store them. Fortunately it is quite easy to store compressed JPG and PNG images inside a database using TWICImage.

The TWICImage component has been available since Delphi 2010, and it uses Windows DirectX to determine and handle multiple image formats. It is actually an encapsulation of the Windows Imaging Component (WIC). We can use TWICImage to determine the type of an image and have it create a correct image format header. We can then save this header + image into a blob field.


procedure SavePictureFileToField(PictureFile: TFileName; Field: TBlobField);
var
  lWICImage: TWICImage;

begin
  lWICImage := TWICImage.Create;
  lWICImage.LoadFromFile(PictureFile);
  Field.Assign(lWICImage);
  lWICImage.Free;
end;

When we later read this image from the blob field, we use TWICImage to interpret the header and then assign it into a TImage.Picture for display.


procedure LoadPictureFromField(Field: TBlobField; Picture: TPicture);
var
  lWICImage: TWICImage;

begin
  if (Field.BlobSize > 0) then
  begin {Assume image}
    lWICImage := TWICImage.Create;
    lWICImage.Assign(Field);
    Picture.Assign(lWICImage);
    lWICImage.Free;
  end
  else {Empty}
  begin
    Picture.Assign(nil);
  end;
end;

And that’s all.

This code will work for any Delphi version starting from Delphi 2010.

Please note that if you are creating a multi-device / FireMonkey application you should not use TWICImage, the FireMonkey TImage and TImageControl both already handle all types of images just fine themselves and going through TWICImage would not be of benefit, in fact it would lock you into Windows.

Completed source code as a simple VCL SQLLite XE7 database application can be downloaded here: DBImage_JPG_PNG

Delphi XE2

Sensationele nieuwe versie FireMonkey waarme je zowel naar Win32/Win64 als naar OSX kunt compileren. Ook voor de VCL is er nu een Win64 compiler. Verder kun je via een FreePascal brug met FireMonkey ook naar iOS mobile devices (iPhone, iPad).