Repository navigation
Expand file tree
/
Copy pathLightCore.Graph.Loader.Resolution.pas
More file actions
516 lines (411 loc) · 14.8 KB
/
Copy pathLightCore.Graph.Loader.Resolution.pas
File metadata and controls
516 lines (411 loc) · 14.8 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
UNIT LightCore.Graph.Loader.Resolution;
{=============================================================================================================
Gabriel Moraru
2026.09.10
www.GabrielMoraru.com
Github.com/GabrielOnDelphi/Delphi-LightSaber/blob/main/System/Copyright.txt
--------------------------------------------------------------------------------------------------------------
Retrieve image resolution without decoding the entire image.
This is done by opening the binary file and reading the file header.
Super mega fast!
Supported formats: JPG, PNG, GIF, BMP.
Returns -1 for Width/Height when format is not supported or file is corrupted.
Framework-neutral: only the RTL and LightCore units. Compiles for the VCL, FMX, a console tool and Android.
The VCL-bound GetBitsPerPixel(TBitmap) stayed behind in LightVcl.Graph.Loader.Resolution.pas.
-------------------------------------------------------------------------------------------------------------}
INTERFACE
USES
System.SysUtils, System.Classes, System.AnsiStrings;
TYPE
TBitmapHeader = Record
Signature : Array[0..1] Of AnsiChar;
Size : Integer;
Reserved : Integer;
OffBits : Integer;
StructSize : Integer;
Width : Integer;
Height : Integer;
Planes : Word;
BitCount : Word;
Compression : Integer;
ImageSize : Integer;
XPelsPerMeter : Integer;
YPelsPerMeter : Integer;
ClrUsed : Integer;
ClrImportant : Integer;
end;
{ Image resolution all }
procedure GetImageRes(CONST FileName: string; OUT Width, Height: Integer); overload;
procedure GetImageRes(CONST FileName: string; Stream: TStream; OUT Width, Height: Integer); overload;
{ Image resolution by stream }
function GetJpgSize (Stream: TStream; OUT Width, Height: Integer): Boolean; overload;
procedure GetPNGSize (Stream: TStream; OUT Width, Height: Integer); overload;
procedure GetGIFSize (Stream: TStream; OUT Width, Height: Integer); overload;
procedure GetBmpSize (Stream: TStream; OUT Width, Height: Integer); overload;
{ Image resolution by file }
function GetJPGSize (CONST Filename: string; OUT Width, Height: Integer): Boolean; overload;
procedure GetPNGSize (CONST FullName: string; OUT Width, Height: Integer); overload;
procedure GetGIFSize (CONST FullName: string; OUT Width, Height: Integer); overload;
procedure GetBmpSize (CONST FullName: string; OUT Width, Height: Integer); overload;
{ BMP info }
function GetBmpHeader (Stream: TStream): TBitmapHeader; // Used by GetBmpSize
IMPLEMENTATION
USES LightCore.Binary, LightCore.IO;
{--------------------------------------------------------------------------------------------------
GET IMAGE RESOLUTION ALL
GetImageRes MUST return -1 to indicate that it tried to read the file but it failed. Otherwise, if it would return 0, the Playlist will keep reading img resolution in grid.draw (many times per second)
--------------------------------------------------------------------------------------------------}
procedure GetImageRes(CONST FileName: string; OUT Width, Height: Integer);
begin
TRY
if IsJpg(FileName)
then GetJPGSize(FileName, Width, Height)
else
if IsPng(FileName)
then GetPNGSize(FileName, Width, Height)
else
if IsGif(FileName)
then GetGIFSize(FileName, Width, Height)
else
if Isbmp(FileName)
then GetBmpSize(FileName, Width, Height)
else
begin
{ DO NOT RAISE: caller decides. Unsupported extension is a legitimate "no resolution" outcome
(e.g. server returned HTML instead of an image during a download). }
Width := -1;
Height:= -1;
end;
EXCEPT
{ Broad swallow is intentional: API contract is "return -1 on any failure" so the caller
(often a grid that polls many times per second) doesn't have to deal with parse errors. }
Width := -1;
Height:= -1;
END;
end;
procedure GetImageRes(CONST FileName: string; Stream: TStream; OUT Width, Height: Integer);
begin
{ Match the file overload: never propagate parse errors to the caller. Any failure -> -1, -1. }
TRY
if IsJpg(FileName)
then GetJPGSize(Stream, Width, Height)
else
if IsPng(FileName)
then GetPNGSize(Stream, Width, Height)
else
if IsGif(FileName)
then GetGIFSize(Stream, Width, Height)
else
if Isbmp(FileName)
then GetBmpSize(Stream, Width, Height)
else
begin
Width := -1;
Height:= -1;
end;
EXCEPT
Width := -1;
Height:= -1;
END;
end;
{--------------------------------------------------------------------------------------------------
JPG
Parses JPEG stream to find dimensions in SOF (Start Of Frame) marker.
JPEG structure: SOI marker ($FFD8) followed by segments.
Each segment: $FF + marker type + 2-byte length + data.
SOF markers ($FFC0..$FFC3) contain frame dimensions.
--------------------------------------------------------------------------------------------------}
function GetJpgSize(Stream: TStream; OUT Width, Height: Integer): Boolean;
VAR
n: integer;
b: byte;
w: Word;
begin
Width := -1;
Height:= -1;
Result:= FALSE;
{ Check empty file }
n:= Stream.Size-8;
if n<= 0 then EXIT(FALSE);
Stream.Position:= 0; { This is mandatory because we don't know who used this object before and if it left it unwinded }
{ Check invalid format }
Stream.Read(w, 2);
if w<>$D8FF then EXIT(FALSE);
Stream.Read(b, 1);
while (Stream.Position< n) AND (b= $FF) DO
begin
Stream.Read(b, 1);
case b of
$C0..$C3:
begin
Stream.Seek(3, soFromCurrent);
{ Get Height }
Stream.Read(w,2);
height := swap(w);
{ Get Width }
Stream.Read(w, 2);
width := swap(w);
{ Success }
EXIT(TRUE);
end;
$D0..$D9, $01:
begin
Stream.Seek(1, soFromCurrent);
Stream.Read(b, 1);
end;
$FF: Stream.Read(b, 1); { Keep reading }
else
begin
Stream.Read(w, 2);
{ Guard against malformed JPEGs: a segment length < 2 would cause us to seek backward, creating an infinite loop.
Valid JPEG segment lengths include the 2 length bytes themselves. }
if swap(w) < 2 then EXIT(FALSE);
Stream.Seek(swap(w)-2, soFromCurrent);
Stream.Read(b, 1);
end;
end;
end;
end;
function GetJPGSize(CONST Filename: string; OUT Width, Height: Integer): Boolean; { Works perfectly }
VAR
DiskStream: TFileStream;
begin
DiskStream:= TFileStream.Create(Filename, fmOpenRead OR fmShareDenyNone);
TRY
Result:= GetJPGSize(DiskStream, Width, Height);
FINALLY
FreeAndNil(DiskStream);
END;
end;
{--------------------------------------------------------------------------------------------------
PNG
Reference (verified against PNG spec ISO 15948): http://www.delphidabbler.com/tips/201
--------------------------------------------------------------------------------------------------}
procedure GetPNGSize(Stream: TStream; OUT Width, Height: Integer);
TYPE
TPNGSig = array[0..7] of Byte;
CONST
ValidSig: TPNGSig = (137,80,78,71,13,10,26,10); {or as hex: 89 50 4E 47 0D 0A 1A 0A }
VAR
FileSign: TPNGSig;
i: integer;
W32, H32: Cardinal;
begin
Width := -1;
Height := -1;
Stream.Position:= 0; { This is mandatory because we don't know who used this object before and if it left it unwinded }
{ Transfer data from MemoryStream to FileSign }
if Stream.Read(FileSign[0], SizeOf(FileSign)) <> 8 then EXIT;
{ Check if the signature is valid }
for i:= Low(FileSign) to High(FileSign) DO
if FileSign[i] <> ValidSig[i] then EXIT;
{ Read image dimensions from IHDR chunk.
PNG layout: 8-byte signature + 4-byte chunk length + 4-byte chunk type ("IHDR") + chunk data.
IHDR data: Width (4 bytes, big-endian) at file offset 16, Height (4 bytes, big-endian) at offset 20. }
TRY
Stream.Seek(16, 0);
W32:= LightCore.Binary.ReadMotorolaCardinal(Stream);
Stream.Seek(20, 0);
H32:= LightCore.Binary.ReadMotorolaCardinal(Stream);
EXCEPT
{ Truncated IHDR - leave Width/Height at -1 }
EXIT;
END;
{ Result is Integer; clamp absurd values that exceed the spec's 2^31-1 maximum.
Caller treats Width=-1 as "failure"; no need to log here.
Cast to Cardinal silences W1023 (signed/unsigned comparison) — MaxInt fits in Cardinal. }
if (W32 > Cardinal(MaxInt)) OR (H32 > Cardinal(MaxInt)) then EXIT;
Width := Integer(W32);
Height := Integer(H32);
end;
procedure GetPNGSize(const FullName: string; OUT Width, Height: Integer);
VAR Stream: TFileStream;
begin
Stream := TFileStream.Create(FullName, fmOpenRead OR fmShareDenyNone);
TRY
GetPNGSize(Stream, Width, Height);
FINALLY
FreeAndNil(Stream);
end;
end;
{--------------------------------------------------------------------------------------------------
GIF
--------------------------------------------------------------------------------------------------}
procedure GetGIFSize(Stream: TStream; OUT Width, Height: Integer); { Also see this (for GIF): http://www.delphipages.com/forum/showthread.php?t=202158 }
TYPE
{ Both records are read directly from disk via Stream.Read(rec, SizeOf(rec)); they MUST be packed
or Delphi adds trailing alignment padding (Word fields force size up to a multiple of 2),
making us consume extra bytes from the stream and shift subsequent parsing. }
TGIFHeader = packed record
Sig: array[0..5] of Ansichar;
ScreenWidth, ScreenHeight: Word;
Flags, Background, Aspect: Byte;
end;
TGIFImageBlock = packed record
Left, Top, Width, Height: Word;
Flags: Byte;
end;
VAR
Header: TGifHeader;
ImageBlock: TGifImageBlock;
nResult: integer;
x: integer;
car: AnsiChar;
DimensionsFound: boolean;
begin
Width := -1;
Height := -1;
Stream.Position:= 0; { This is mandatory because we don't know who used this object before and if it left it unwinded }
{ Read header and ensure valid file. }
nResult:= Stream.Read(Header, SizeOf(TGifHeader));
if (nResult <> SizeOf(TGifHeader))
OR (System.AnsiStrings.StrLComp('GIF', Header.Sig, 3) <> 0)
then Exit; { Image file invalid }
{ Skip color map, if there is one.
Bit 7 of Flags indicates presence of Global Color Table.
Bits 0-2 indicate size: 2^(N+1) colors, 3 bytes each (RGB). }
if (Header.Flags and $80) > 0 then
begin
x := 3 * (1 shl ((Header.Flags and 7) + 1));
if Stream.Position + x >= Stream.Size then EXIT; { Color map thrashed }
Stream.Seek(x, soFromCurrent);
end;
DimensionsFound := False;
FillChar(ImageBlock, SizeOf(TGIFImageBlock), #0);
{ Step through blocks. }
Stream.Read(car, 1);
WHILE (Stream.Position < Stream.Size) AND NOT DimensionsFound DO
begin
if car = ',' then { Found image }
begin
nResult:= Stream.Read(ImageBlock, SizeOf(TGIFImageBlock));
if nResult <> SizeOf(TGIFImageBlock) then Exit; { Invalid image block encountered }
Width := ImageBlock.Width;
Height:= ImageBlock.Height;
DimensionsFound := True;
end;
Stream.Read(car, 1);
end;
end;
procedure GetGIFSize(CONST FullName: string; OUT Width, Height: Integer);
VAR
Stream: TFileStream;
begin
Stream := TFileStream.Create(FullName, fmOpenRead OR fmShareDenyNone);
TRY
GetGIFSize(Stream, Width, Height);
FINALLY
FreeAndNil(Stream);
END;
end;
{ NOTE: IsAnimatedGif moved to GifProperties.pas (External). }
{--------------------------------------------------------------------------------------------------
BMP
--------------------------------------------------------------------------------------------------}
{ Retrieves BMP dimensions from file by reading the BMP header.
Source: http://www.delphipages.com/forum/archive/index.php/t-202158.html }
procedure GetBmpSize(CONST FullName: string; OUT Width, Height: Integer);
VAR
H: TBitmapHeader;
Stream: TFileStream;
begin
Stream:= TFileStream.Create(FullName, fmOpenRead OR fmShareDenyNone);
TRY
H:= GetBmpHeader(Stream);
if H.Signature = 'BM' then
begin
Width := H.Width;
{ Top-down DIBs encode Height as a negative value; pixel height is the absolute value.
The raw signed value stays in the TBitmapHeader record; callers asking for pixel dims get Abs. }
Height:= Abs(H.Height);
end
else
begin
Width := -1;
Height:= -1;
end;
FINALLY
FreeAndNil(Stream);
END;
end;
procedure GetBmpSize(Stream: TStream; OUT Width, Height: Integer);
VAR H: TBitmapHeader;
begin
H:= GetBmpHeader(Stream);
if H.Signature = 'BM' then
begin
Width := H.Width;
Height:= Abs(H.Height);
end
else
begin
Width := -1;
Height:= -1;
end;
end;
{ Reads and parses a BMP file header from a stream.
BMP format: 2-byte signature ("BM") followed by BITMAPFILEHEADER and BITMAPINFOHEADER.
Returns a TBitmapHeader record with -1 values if the signature is invalid. }
function GetBmpHeader(Stream: TStream): TBitmapHeader;
VAR
CTemp: AnsiChar;
Lng: LongInt;
Wrd: Word;
begin
CTemp := '.';
Stream.Position:= 0; { Reset stream position - mandatory because we don't know who used this object before }
Stream.ReadBuffer(CTemp,1);
Result.Signature[0]:= CTemp;
Stream.ReadBuffer(CTemp,1);
Result.Signature[1]:= CTemp;
if Result.Signature = 'BM' then
begin
Stream.ReadBuffer(Lng,4); //Size
Result.Size := Lng;
Stream.ReadBuffer(Lng,4); //Reserved
Result.Reserved := Lng;
Stream.ReadBuffer(Lng,4); //OffBits
Result.OffBits := Lng;
Stream.ReadBuffer(Lng,4); //StructSize
Result.StructSize := Lng;
Stream.ReadBuffer(Lng,4); //Width
Result.Width := Lng;
Stream.ReadBuffer(Lng,4); //Height
Result.Height := Lng;
Stream.ReadBuffer(Wrd,2); //Planes
Result.Planes := Wrd;
Stream.ReadBuffer(Wrd,2); //BitCount
Result.BitCount:= Wrd;
Stream.ReadBuffer(Lng,4); //Compression
Result.Compression := Lng;
Stream.ReadBuffer(Lng,4); //Image Size
Result.ImageSize := Lng;
Stream.ReadBuffer(Lng,4); //XPels
Result.XPelsPerMeter := Lng;
Stream.ReadBuffer(Lng,4); //YPels
Result.YPelsPerMeter := Lng;
Stream.ReadBuffer(Lng,4); //CLRUsed
Result.ClrUsed := Lng;
Stream.ReadBuffer(Lng,4); //CLRImportant
Result.ClrImportant := Lng;
end
else
begin
{ Invalid BMP signature - return -1 for all size-related fields }
Result.Size := -1;
Result.Reserved := -1;
Result.OffBits := -1;
Result.StructSize := -1;
Result.Width := -1;
Result.Height := -1;
Result.Planes := 0;
Result.BitCount := 0;
Result.Compression := -1;
Result.ImageSize := -1;
Result.XPelsPerMeter := -1;
Result.YPelsPerMeter := -1;
Result.ClrUsed := -1;
Result.ClrImportant := -1;
end;
end;
end.