Save and Use images in database ( Delphi and Mysql)

Asked

Viewed 4,217 times

1

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 display the images already saved in the database. Where the image is stored in Mysql is of the type blob.

Thank you!

1 answer

1


Friend, by own experience I strongly suggest you save the images in a directory and save in the database only the path of the directory. Save to database forces growth disorderly bank, difficult maintenance, backups (dumps, for example) among other obstacles.
However, if you want or need to continue saving in the bank, follow some code alternatives:
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 BMP s, 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; 
  • Thanks Andrey, it worked perfectly, however, only records images of type . bmp, other images, for example . jpg is not possible and also images that already exist in the database (like .jpg) are not displayed in Dbimage. ERROR: Bitmap image is not a Valid. Would you know how to fix this? I can’t tell if it’s a Dbimage error when it displays the contents of the database.

  • What happens is that Dbimage only works with bmp even... with other extensions is incompatible. Solution: Gambiarra. I will edit the answer with an alternative consisting of loading a jpg, but converting it to bmp to be displayed in Dbimage. If the answer answered the question, remember to accept it.

  • The solution would be to convert before saving to BD and save it as BMP already...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.