Write and Use images in database (Delphi and MySQL)

1

Hello, I would like to know how to write 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 blob type.

Thank you!

    
asked by anonymous 13.02.2018 / 17:54

1 answer

1

Friend, from experience I strongly suggest you save the images to a directory and save only the directory path to the database. Saving to the database forces the database to grow disorderly, hinders maintenance, dumps, for example), among other obstacles.
However, if you want or need to continue saving in the bank, there are some code alternatives:
DBImage1.Picture.LoadFromFile('c:\pasta\imagem.jpg');
or Source: link )

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; 
    
13.02.2018 / 20:25