Registriert seit: 19. Jan 2009
Ort: Kirchlinteln (LK Verden)
1.086 Beiträge
Delphi 2009 Professional
|
AW: Sichere Erkennung von PNG bzw. JPG?
15. Mär 2022, 19:13
In neueren Delphis haben die Grafikklassen das glaube ich selbst.
Ansonsten:
Delphi-Quellcode:
type TImageFormat = (unknown, BMP, GIF, JPG, PNG);
function GetImageFormat(Stream: TStream): TImageFormat;
var
Memory: array[0..8] of Byte;
begin
Result := unknown;
try
if Stream.Size < 10 then
Exit;
Stream.Position := 0;
Stream.Read(Memory, 9);
case Memory[0] of
66: if Memory[1] = 77 then // BM: Bitmap
Result := BMP;
137: if Memory[1] = 80 then // ‰PNG: PNG
if Memory[2] = 78 then
if Memory[3] = 71 then
if Memory[4] = 13 then
if Memory[5] = 10 then
if Memory[6] = 26 then
if Memory[7] = 10 then
Result := PNG;
71: if Memory[1] = 73 then // GIF8...a
if Memory[2] = 70 then
if Memory[3] = 56 then
if Memory[5] = 97 then
case Memory[4] of
55: Result := GIF; // 7: GIF, old
57: Result := GIF; // 9: GIF, new
end;
255: if Memory[1] = 216 then // ÿØ: JPEG
Result := JPG;
end;
except
end;
Stream.Position := 0;
end;
function LoadImageFromStream(Target: TPersistent; Stream: TStream): Boolean;
var
GraphicClass: TGraphicClass;
Graphic: TGraphic;
begin
Result := False;
case GetImageFormat(Stream) of
BMP: GraphicClass := Graphics.TBitmap;
PNG: GraphicClass := TPNGImage;
JPG: GraphicClass := TJPEGImage;
GIF: GraphicClass := TGIFImage;
else raise EInvalidGraphic.CreateFmt(SInvalidImage, []);
end;
if not (GraphicClass = nil) then
begin
Graphic := GraphicClass.Create;
try
Graphic.LoadFromStream(Stream);
Target.Assign(Graphic);
Result := True;
finally
Graphic.Free;
end;
end;
end;
Janni 2005 PE, 2009 PA, XE2 PA
|
|
Zitat
|