1 16 package org.apache.cocoon.components.source.impl; 17 18 import java.io.BufferedInputStream ; 19 import java.io.IOException ; 20 21 import org.apache.avalon.framework.thread.ThreadSafe; 22 import org.apache.excalibur.source.Source; 23 import org.apache.excalibur.source.SourceException; 24 25 32 public class JPEGSourceInspector extends AbstractImageSourceInspector implements ThreadSafe { 33 34 35 public JPEGSourceInspector() { 36 } 37 38 41 protected final boolean isImageMimeType(Source source) { 42 final String uri = source.getURI(); 43 final int index = uri.lastIndexOf('.'); 44 if (index != -1) { 45 String extension = uri.substring(index); 46 return extension.equalsIgnoreCase(".jpg") || extension.equalsIgnoreCase(".JPEG"); 47 } 48 return false; 49 } 50 51 54 protected final boolean isImageFileType(Source source) throws SourceException { 55 BufferedInputStream in = null; 56 try { 57 in = new BufferedInputStream (source.getInputStream()); 58 byte[] buf = new byte[2]; 59 int count = in.read(buf, 0, 2); 60 if (count < 2) 61 return false; 62 63 if ((buf[0] == (byte)0xFF) && 64 (buf[1] == (byte)0xD8)) 65 return true; 66 } catch (IOException ioe) { 67 throw new SourceException("Could not read source", ioe); 68 } finally { 69 if (in != null) 70 try { 71 in.close(); 72 } catch(Exception e) {} 73 } 74 return false; 75 } 76 77 80 protected final int[] getImageSize(Source source) throws SourceException { 81 BufferedInputStream in = null; 82 try { 83 in = new BufferedInputStream (source.getInputStream()); 84 byte[] buf = new byte[2]; 86 int count = in.read(buf, 0, 2); 87 if (count < 2) throw new SourceException("Not a valid Jpeg file!"); 88 if((buf[0]) != (byte)0xFF 89 || (buf[1]) != (byte)0xD8 ) 90 throw new SourceException("Not a valid Jpeg file!"); 91 92 int width = 0; 93 int height = 0; 94 95 boolean done = false; 96 int ch = 0; 97 98 try { 99 while(ch != 0xDA && !done) { 100 101 while (ch != 0xFF) { ch = in.read(); } 102 103 while (ch == 0xFF) { ch = in.read(); } 104 105 if(ch >= 0xC0 && ch <= 0xC3) { 106 in.read(); 108 in.read(); 109 in.read(); 110 height = 256 * in.read(); 111 height += in.read(); 112 width = 256 * in.read(); 113 width += in.read(); 114 done = true; 115 } else { 116 118 int length = 256 * in.read(); 119 length += in.read(); 120 if(length < 2) throw new RuntimeException ("Erroneous JPEG marker length"); 121 for(int foo = 0; foo<length-2; foo++) 122 in.read(); 123 } 124 } 125 } catch (Exception e) { 126 throw new SourceException("Not a valid Jpeg file!", e); 127 } 128 129 int[] dim = { width, height }; 130 return dim; 131 132 } catch (IOException ioe) { 133 throw new SourceException("Could not read source", ioe); 134 } finally { 135 if (in != null) 136 try { 137 in.close(); 138 } catch (Exception e) {} 139 } 140 } 141 142 } 143 144 | Popular Tags |