I'm writing a simple app to load images and save it to a Blob
field in a database , and retrieve the image again when needed.
Here is my code :
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs , Vcl.StdCtrls, Vcl.ExtCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.MSAcc, FireDAC.Phys.MSAccDef, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB,
Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ExtDlgs ,Vcl.Imaging.jpeg , pngimage;
type
TForm1 = class(TForm)
Image1: TImage;
Load: TButton;
FDConnection1: TFDConnection;
FDTable1: TFDTable;
DataSource1: TDataSource;
FDTable1ID: TFDAutoIncField;
FDTable1IMG: TBlobField;
DBGrid1: TDBGrid;
Write: TButton;
Read: TButton;
Image2: TImage;
OpenPictureDialog1: TOpenPictureDialog;
procedure LoadClick(Sender: TObject);
procedure WriteClick(Sender: TObject);
procedure ReadClick(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
Pic , Graph : TPicture;
Stream1 : TStream;
implementation
{$R *.dfm}
procedure TForm1.LoadClick(Sender: TObject);
begin
//Create Tpicture
Pic := TPicture.Create;
try
// Load from file
if OpenPictureDialog1.Execute then
begin
Pic.LoadFromFile(OpenPictureDialog1.FileName);
// Assign Image1 to Pic
Image1.Picture.Assign(Pic);
// Stretch
Image1.Stretch := True;
end;
Except on E : Exception do
ShowMessage(E.Message);
end;
end;
procedure TForm1.WriteClick(Sender: TObject);
begin
Stream1 := TStream.Create;
try
// With .JPG , .BMP files it works fine , But not workin with .PNG , .ICO files
Pic.Graphic.SaveToStream(Stream1);
FDTable1.Append;
Stream1 := FDTable1.CreateBlobStream(FDTable1IMG , bmWrite);
FDTable1.Post;
finally
Stream1.Free;
Pic.Free;
end;
end;
procedure TForm1.ReadClick(Sender: TObject);
begin
Graph := TPicture.Create;
try
Graph.Assign(FDTable1IMG);
Image2.Picture.Assign(Graph); //<-- here is the problem , Nothing shown in the TImage control
finally
Graph.Free;
end;
end;
end.
I have two problems here :
First :
InWriteClick
procedure when I try to save.JPG
or.bmp
files , the code run without errors , and the image saved to the database , but when I try to sae.ICO
or.PNG
files, I the following error :Write error in stream
Second :
In ReadClick
procedure , when I assign Graph
to the Image2
control , Nothing shown in the TImage control, and there is no error Msg.
How can fix this problems? What I'm doing wrong?