Since 0xFFD9 is not necessary to be present in JPEG image (as EOF marker) and even if it is present it might give incorrect result due to embedded thumbnail in jpeg, so I need to parse JPEG to extract any appended data (e,g zip). I have following java code based on the assumption that a marker will be followed by 2 byte length. But this is not the case with SOS segment i.e. 0xFFDA marker. How can i detect EOF in JPEG?
public String getJPEGAppendedData(DataInputStream in) {
StringBuilder message = new StringBuilder();
try {
// reading first two bytes 0xFFD8
in.readFully(new byte[2]);
// 0xFFXX
byte twoBytes[] = new byte[2];
while (true) {
in.readFully(twoBytes);
if (twoBytes[0] == (byte) 0xFF) {
if (twoBytes[1] == (byte) 0xDD) {
// fixed 4 bytes payload
in.readFully(new byte[4]);
} else if (twoBytes[1] == (byte) 0xD9) {
// end of image reached
break;
} else if (twoBytes[1] >= (byte) 0xD0 && twoBytes[1] <= (byte) 0xD7) {
// no payload
} else {
// reading payload length form two bytes
short length = in.readShort();
System.out.println(length);
// skipping payload
for (int i = 1; i <= length - 2; i++) {
in.readByte();
}
}
} else {
break;
}
}
// reading appended data (byte by byte) if any
boolean moreData = true;
while (moreData) {
try {
byte b = in.readByte();
message.append(String.format("%02X", b));
} catch (Exception e) {
moreData = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return message.toString();
}