try {
in = new BufferedInputStream(source.getInputStream());
// check for "magic" header
byte[] buf = new byte[2];
int count = in.read(buf, 0, 2);
if (count < 2) throw new SourceException("Not a valid Jpeg file!");
if((buf[0]) != (byte)0xFF
|| (buf[1]) != (byte)0xD8 )
throw new SourceException("Not a valid Jpeg file!");
int width = 0;
int height = 0;
boolean done = false;
int ch = 0;
try {
while(ch != 0xDA && !done) {
/* Find next marker (JPEG markers begin with 0xFF) */
while (ch != 0xFF) { ch = in.read(); }
/* JPEG markers can be padded with unlimited 0xFF's */
while (ch == 0xFF) { ch = in.read(); }
/* Now, ch contains the value of the marker. */
if(ch >= 0xC0 && ch <= 0xC3) {
// skip 3 bytes
in.read();
in.read();
in.read();
height = 256 * in.read();
height += in.read();
width = 256 * in.read();
width += in.read();
done = true;
} else {
/* We MUST skip variables, since FF's within variable names
are NOT valid JPEG markers */
int length = 256 * in.read();
length += in.read();
if(length < 2) throw new RuntimeException("Erroneous JPEG marker length");
for(int foo = 0; foo<length-2; foo++)
in.read();
}
}
} catch (Exception e) {
throw new SourceException("Not a valid Jpeg file!", e);
}
int[] dim = { width, height };
return dim;
} catch (IOException ioe) {
throw new SourceException("Could not read source", ioe);
} finally {
if (in != null)
try {
in.close();
} catch (Exception e) {}