由于JPEG图像中不需要0xFFD9(作为EOF标记),即使它存在,由于jpeg中嵌入的缩略图,它可能会给出错误的结果,因此我需要解析JPEG以提取任何附加数据(e ,g zip)。我有以下java代码,假设标记后面跟着2个字节的长度。但这不是SOS段的情况,即0xFFDA标记。如何在JPEG中检测EOF?
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();
}