-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathDN.Graphics.Loader.pas
110 lines (98 loc) · 2.53 KB
/
DN.Graphics.Loader.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
unit DN.Graphics.Loader;
interface
uses
Classes,
Types,
Graphics;
type
TGraphicLoader = class
protected
class function TryCreateGraphic(const AExtension: string; out AGraphic: TGraphic): Boolean;
public
class function TryCreateFromFile(const AFileName: string; out AGraphic: TGraphic): Boolean;
class function TryCreateFromStream(const AStream: TStream; const AExtension: string; out AGraphic: TGraphic): Boolean;
class function TryLoadPictureFromFile(const AFileName: string; APicture: TPicture): Boolean;
class function TryLoadPictureFromStream(const AStream: TStream; const AExtension: string; const APicture: TPicture): Boolean;
end;
implementation
uses
PNGImage,
JPeg,
SysUtils,
StrUtils,
IOUtils;
{ TGraphicLoader }
class function TGraphicLoader.TryCreateFromFile(const AFileName: string;
out AGraphic: TGraphic): Boolean;
begin
Result := False;
if TFile.Exists(AFileName) and TryCreateGraphic(ExtractFileExt(AFileName), AGraphic) then
begin
try
AGraphic.LoadFromFile(AFileName);
Result := True;
except
on EInvalidGraphic do
AGraphic.Free;
end;
end;
end;
class function TGraphicLoader.TryCreateFromStream(const AStream: TStream;
const AExtension: string; out AGraphic: TGraphic): Boolean;
begin
Result := False;
if TryCreateGraphic(AExtension, AGraphic) then
begin
try
AGraphic.LoadFromStream(AStream);
Result := True;
except
on E: EInvalidGraphic do
FreeAndNil(AGraphic);
end;
end;
end;
class function TGraphicLoader.TryCreateGraphic(const AExtension: string;
out AGraphic: TGraphic): Boolean;
begin
Result := True;
case AnsiIndexText(AExtension, ['.png', '.jpg', '.jpeg']) of
0: AGraphic := TPngImage.Create();
1, 2: AGraphic := TJPEGImage.Create();
else
Result := False;
end;
end;
class function TGraphicLoader.TryLoadPictureFromFile(const AFileName: string;
APicture: TPicture): Boolean;
var
LGraphic: TGraphic;
begin
Result := False;
if TryCreateFromFile(AFileName, LGraphic) then
begin
try
APicture.Graphic := LGraphic;
Result := True;
finally
LGraphic.Free;
end;
end;
end;
class function TGraphicLoader.TryLoadPictureFromStream(const AStream: TStream;
const AExtension: string; const APicture: TPicture): Boolean;
var
LGraphic: TGraphic;
begin
Result := False;
if TryCreateFromStream(AStream, AExtension, LGraphic) then
begin
try
APicture.Graphic := LGraphic;
Result := True;
finally
LGraphic.Free;
end;
end;
end;
end.