J2K files have 4 compulsory top-level boxes. They are
- JPEG 2000 signature box
- File Type box
- JP2 Header box
- Contiguous Codestream box
Each box is preceded by 4 byte marker and 4 byte size value. So in MATLAB it should be something like this
fname='C:\Users\admin\Documents\MATLAB\SO\Jpeg2k\balloon.jp2';
fid = fopen(fname);
headerMark = uint8('jp2h');
matchCnt = 1;
ch = fread(fid,1,'*uint8');
matchCnt = matchCnt+isequal(headerMark(1),ch);
while matchCnt < 5 && ~feof(fid)
ch = fread(fid,1,'*uint8');
matchCnt = matchCnt+isequal(headerMark(matchCnt),ch);
end
if matchCnt == 5
fseek(fid,ftell(fid)-8,'bof');
sizeBytes = fread(fid,4,'*uint8');
sizeVal = arrayfun(@(x,y) bitshift(x,y,32), uint32(sizeBytes), [3:-1:0]');
sizeVal = bitor(bitor(bitor(sizeVal(1),sizeVal(2)),sizeVal(3)),sizeVal(4));
end
fclose(fid);
I don't know what is you final task (getting header size seems to be halfway) but I recommend to see the quickstart guide for JPEG2000, JPEG2000 validator (written in python) and the validator overview.