Upload a png image to Image from the SQL database (Delphi)

Such a problem.I've searched the entire Internet and can't find anything. How to upload an image from an SQL Database to Image. Here is the picture selection:enter a description of the image here

P.S. Image post type MediumBlob

Author: Program_Casual, 2018-06-13

1 answers

Try it like this:

uses
  PNGImage;

procedure TForm1.Button1Click(Sender: TObject);
var
  VPng: TGraphic;
begin
  VPng := TPNGObject.Create; // или TPNGImage.Create; если Delphi XE2 и выше
  try
    ...
    SQLQuery1.Open;

    VPng.Assign(SQLQuery1.FieldByName('photo'));
    Image1.Picture.Assign(VPng);
  finally
    VPng.Free;
  end;
end;

The PNGImage component is built-in in new versions of Delphi, and for older versions you can take it here: https://github.com/JackTrapper/pngdelphi


Alternative method, via an intermediate TStream:

var      
  VPng: TGraphic;
  VStream: TStream;
begin
  VPng := TPNGObject.Create;
  try
    ...
    SQLQuery1.Open;

    VStream := SQLQuery1.CreateBlobStream(SQLQuery1.FieldByName('photo'), bmRead);
    try
      // тут VStream можно сохранить на диск или сделать 
      // какие-то дополнительные проверки формата изображения

      VPng.LoadFromStream(VStream);
      Image1.Picture.Assign(VPng);
    finally
      VStream.Free;
    end;
  finally
    VPng.Free;
  end;
end;
 1
Author: zed, 2018-06-14 06:39:45