Gallery
Software
Music
Programming
Archive
Saturday, Feb 23 Week 8

PNG file information

Read basic file info from a bitmap file using Windows API...

TPngHeader structure

type
pPngHeader=^TPngHeader;
TPngHeader=packed record
uSig :int64; //int64($0A1A0A0D474E5089);
uChunk1Len :longWord; //reverse byte order
uChunk1Type :longWord; //IHDR: $52444849
uWidth :longWord; //reverse byte order
uHeight :longWord; //reverse byte order
uBitDepth :byte; //1, 2, 4, 8 or 16
uColorType :byte; //0, 2, 3, 4 or 6
uCompression :byte;
uFilter :byte;
uInterlace :byte;
end;

Constants

const
iPngSig:int64=$0A1A0A0D474E5089; //signature
uPngIHDR:longWord=$52444849;

Color mode (image format)

# ID Title Description
0 Grayscale 8-Bit Grayscale
2 RGB 24-Bit RGB color
3 Indexed 8-Bit Indexed palette
4 Grayscale 8-Bit + Alpha Grayscale with alpha channel
6 RGBA 32-Bit RGB color with alpha channel

Read file header into memory

//Read header from a file into preallocated buffer of a given size...
//from: http://www.mortenbs.com/delphi-read-file-header/
function readFileHeader(pFileName:pAnsiChar;pBuf:pointer;uSize:longWord):boolean;
const ac=GENERIC_READ;sh=FILE_SHARE_READ;attr=FILE_ATTRIBUTE_READONLY;
var h:THandle;n:longWord;
begin
result:=false;
if (pFileName=nil) or (pBuf=nil) or (uSize=0) then exit;
h:=windows.createFileA(pFileName,ac,sh,nil,OPEN_EXISTING,attr,0); //open read
if h<>INVALID_HANDLE_VALUE then begin
result:=windows.readFile(h,pBuf^,uSize,n,nil) and (n=uSize);
windows.closeHandle(h); //close
end;
end;

Byte swap, 32-Bits

function bswap32(n:longWord):longWord; //reverse byte order
begin
result:=byte(n shr 24)
or (byte(n shr 16) shl 8)
or (byte(n shr 8) shl 16)
or (byte(n) shl 24)
end;

Read PNG file info

function png_fileinfo(filename:ansiString;memo:TMemo):bool;
var sz:longWord;buf:TPngHeader;
begin
result:=false;
sz:=sizeOf(TPngHeader);
if not readFileHeader(pAnsiChar(filename),@buf,sz) then exit;
with buf do begin
if uSig<>iPngSig then exit; //unknown format
memo.lines.add('filename='+filename);
memo.lines.add('width='+intToStr(bswap32(uWidth))); //ex.: 48 px
memo.lines.add('height='+intToStr(bswap32(uHeight))); //ex.: 48 px
memo.lines.add('bitres='+intToStr(uBitDepth)); //1, 2, 4, 8 or 16
memo.lines.add('colortype='+intToStr(uColorType)); //0, 2, 3, 4 or 6
memo.lines.add('compression='+intToStr(uCompression));
end;
result:=true;
end;

Example: Read PNG file info

procedure TForm1.FormCreate(Sender: TObject);
var filename:ansiString;
begin
memo1.clear;
filename:='C:\sample.png';
if not png_fileinfo(filename,memo1) then memo1.text:='error';
end;

Related pages of PNG file information

Programming
Delphi programming
Colors and formats
File formats and fileinfo
Read file header into memory
BMP Bitmap file info