1 51 package org.apache.fop.image.analyser; 52 53 import java.io.BufferedInputStream ; 55 import java.io.IOException ; 56 57 62 public class JPEGReader extends AbstractImageReader { 63 64 71 protected static final int MARK = 0xff; protected static final int NULL = 0x00; protected static final int SOF1 = 0xc0; protected static final int SOF2 = 0xc1; protected static final int SOF3 = 0xc2; protected static final int SOFA = 0xca; protected static final int APP0 = 0xe0; protected static final int APPF = 0xef; protected static final int SOS = 0xda; protected static final int SOI = 0xd8; protected static final int JPG_SIG_LENGTH = 2; 82 83 protected byte[] header; 84 85 public boolean verifySignature(String uri, BufferedInputStream fis) 86 throws IOException { 87 this.imageStream = fis; 88 this.setDefaultHeader(); 89 boolean supported = ((header[0] == (byte)0xff) 90 && (header[1] == (byte)0xd8)); 91 if (supported) { 92 setDimension(); 93 return true; 94 } else 95 return false; 96 } 97 98 public String getMimeType() { 99 return "image/jpeg"; 100 } 101 102 protected void setDefaultHeader() throws IOException { 103 this.header = new byte[JPG_SIG_LENGTH]; 104 try { 105 this.imageStream.mark(JPG_SIG_LENGTH + 1); 106 this.imageStream.read(header); 107 this.imageStream.reset(); 108 } catch (IOException ex) { 109 try { 110 this.imageStream.reset(); 111 } catch (IOException exbis) {} 112 throw ex; 113 } 114 } 115 116 protected void setDimension() throws IOException { 117 try { 118 int marker = NULL; 119 long length, skipped; 120 outer: 121 while (imageStream.available() > 0) { 122 while ((marker = imageStream.read()) != MARK) { 123 ; 124 } 125 do { 126 marker = imageStream.read(); 127 } while (marker == MARK); 128 switch (marker) { 129 case SOI: 130 break; 131 case NULL: 132 break; 133 case SOF1: 134 case SOF2: 135 case SOF3: case SOFA: 137 this.skip(3); 138 this.height = this.read2bytes(); 139 this.width = this.read2bytes(); 140 break outer; 141 default: 142 length = this.read2bytes(); 143 skipped = this.skip(length - 2); 144 if (skipped != length - 2) 145 throw new IOException ("Skipping Error"); 146 } 147 } 148 } catch (IOException ioe) { 149 try { 150 this.imageStream.reset(); 151 } catch (IOException exbis) {} 152 throw ioe; 153 } 154 } 155 156 protected int read2bytes() throws IOException { 157 int byte1 = imageStream.read(); 158 int byte2 = imageStream.read(); 159 return (int)((byte1 << 8) | byte2); 160 } 161 162 protected long skip(long n) throws IOException { 163 long discarded = 0; 164 while (discarded != n) { 165 imageStream.read(); 166 discarded++; 167 } 168 return discarded; } 170 171 } 172 173 | Popular Tags |