使用Java程序读取JPEG文件(三)
2014-11-24 03:24:22
·
作者:
·
浏览: 2
int GetSectionLen(int iByteHigh, int iByteLow) {
System.out.println("GetSectionLen(" + iByteHigh + ", " + iByteLow + ")");
int iBlockLen = ((iByteHigh << 8) + iByteLow) & 0xffff;
System.out.println("Section length: " + iBlockLen + " bytes");
return iBlockLen;
}
void JumpOverSection(ByteArrayInputStream bais, SectionType eSectionType) {
System.out.println("Section[" + eSectionType + "] jump over");
int iBlockLen = GetSectionLen(bais.read(), bais.read());
bais.skip(iBlockLen - 2);
}
void ReadDQT(ByteArrayInputStream bais) throws IOException{
System.out.println("----------Section[DQT]----------");
System.out.println("Section[DQT] reading ...");
int iBlockLen = GetSectionLen(bais.read(), bais.read());
JDQT dqt = new JDQT();
dqt.m_byQTInfo = (byte)bais.read();
//check validation
//QT
int n = (dqt.m_byQTInfo >> 4) & 0xf;
dqt.ReadQTArray(bais, n);
m_arrDQT.add(dqt);
System.out.println("Section[DQT] read " + (64 * (n + 1) + 1) + " bytes");
System.out.println("");
}
//
ERROR_CODE readFromFile(String sFilename) {
try {
byte[] byteArr = BinaryFile.read(sFilename);
ByteArrayInputStream bais = new ByteArrayInputStream(byteArr);
if (bais.available() < 2) {
System.out.println("File length is too small");
return ERROR_CODE.ERR_OK;
}
//JPEG header
SectionType eSectionType = GetSectionType(bais.read(), bais.read());
if (eSectionType != SectionType.SOI) {
System.out.println("File is not JPEG File");
return ERROR_CODE.ERR_NOT_JEPG_FILE;
}
//Iterate Section
System.out.println("File is JPEGFile");
System.out.println("Start iterating sections ...");
Boolean bStartScanning = false;
while (bais.available() > 0) {
int iByteHigh = bais.read();
int iByteLow = bais.read();
if (bStartScanning) {
continue;
}
eSectionType = GetSectionType(iByteHigh, iByteLow);
switch (eSectionType) {
case NOP:
continue;
case SOF0:
JumpOverSection(bais, eSectionType);
break;
case SOF2:
JumpOverSection(bais, eSectionType);
break;
case DRI:
JumpOverSection(bais, eSectionType);
break;
case DQT:
ReadDQT(bais);
break;
case DHT:
JumpOverSection(bais, eSectionType);
break;
case COM:
JumpOverSection(bais, eSectionType);
break;
case SOS:
bStartScanning = true;
JumpOverSection(bais, eSectionType);
break;
default:
JumpOverSection(bais, eSectionType);
break;
}
}
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return ERROR_CODE.ERR_OK;
}
}
GetSectionType获取段的类型,GetSectionLen获取段的长度,JumpOverSection跳过当前段的数据,ReadDQT读取DQT段的数据。
readFromFile利用BinaryFile读取文件到内存的字节数组,判断JPEG头。如果是JPEG文件,那么逐段的读入数据。我们这里只处理了DQT段,其他的段我们都跳过了;在SOS段我们设置了bStartScanning标示,这个SOS段标示之后就是具体的图像数据,可以开始扫描了。
五、类的使用方法
如下使用此类
public class Hello {
public static void main(String[] args) {
JPEGFile jpg = new JPEGFile();
jpg.readFromFile("JUC801.jpg");
}
}
六、总结
本文提供了最简单的读取JPEG各段的方法,在此基础上可以继续分析JPEG的各个数据段和具体图像数据。