Write and use images in database (Delphi and MySQL)

Hello, I would like to know how to record images (.jpg, .png, .bmp, etc) in the MySQL database, using Delphi XE6.

I would like to use TDBImage if possible to show the images already recorded in the database. Where it stores the image in MySQL is of type blob .

Thank you!

Author: Julio Gaiotto, 2018-02-13

1 answers

Friend, from experience I strongly suggest you save the images in a directory and save in the database only the directory path. Saving in the database forces the growth messy of the bank, hinders maintenance, backups (dumps, for example) among other obstacles.
However, in case you want or need to continue saving to the bank, some code alternatives follow:
DBImage1.Picture.LoadFromFile('c:\pasta\imagem.jpg');
or (Source: https://www.scriptbrasil.com.br/forum/topic/114397-resolvido-gravar-imagens-no-mysql/)

var
  MS :TMemoryStream;
begin
  ...
  if OpenPictureDialog1.Execute then
  begin
    FOTO.Picture.LoadFromFile(OpenPictureDialog1.FileName);
    MS := TMemoryStream.Create;
    try
      FOTO.Picture.Graphic.SaveToStream(MS);
      (DataModule1.Table1.FieldByName('foto') as TBlobField).LoadFromStream(MS);
    finally
      MS.Free;
    end;
  end;
end;

As already mentioned, DBImage is for BMPs , as a palliative solution:

procedure TForm1.DBImage1DblClick(Sender: TObject); 
var 
  JPG:TJPEGImage; 
  BMP:TBitmap; 
begin 
  if OpenDialog1.Execute then 
  begin 
    JPG:= TJPEGImage.Create; 
    JPG.LoadFromFile(OpenDialog1.FileName); 
    BMP:=TBitmap.Create; 
    BMP.Assign(JPG); 
    JPG.Free; 
    dbimage1.Picture.Bitmap.Assign(BMP); 
    bmp.Free; 
  end; 
end; 
 1
Author: Andrey, 2018-02-14 10:59:39