1 package com.nwalsh.saxon; 2 3 import java.io.*; 4 import java.awt.*; 5 import java.awt.image.*; 6 import java.lang.Thread ; 7 import java.util.StringTokenizer ; 8 9 32 public class ImageIntrinsics implements ImageObserver { 33 boolean imageLoaded = false; 34 boolean imageFailed = false; 35 Image image = null; 36 int width = -1; 37 int depth = -1; 38 39 42 public ImageIntrinsics(String imageFn) { 43 System.setProperty("java.awt.headless","true"); 44 image = Toolkit.getDefaultToolkit().getImage (imageFn); 45 width = image.getWidth(this); 46 47 while (!imageFailed && (width == -1 || depth == -1)) { 48 try { 49 java.lang.Thread.currentThread().sleep(50); 50 } catch (Exception e) { 51 } 53 width = image.getWidth(this); 54 depth = image.getHeight(this); 55 } 56 57 if (imageFailed) { 58 BufferedReader ir = null; 61 String line = null; 62 int lineLimit = 100; 63 64 try { 65 ir = new BufferedReader(new FileReader(new File(imageFn))); 66 line = ir.readLine(); 67 68 if (line != null && line.startsWith("%PDF-")) { 69 while (lineLimit > 0 && line != null) { 71 lineLimit--; 72 if (line.startsWith("/CropBox [")) { 73 line = line.substring(10); 74 if (line.indexOf("]") >= 0) { 75 line = line.substring(0, line.indexOf("]")); 76 } 77 parseBox(line); 78 lineLimit = 0; 79 } 80 line = ir.readLine(); 81 } 82 } else if (line != null && line.startsWith("%!") && line.indexOf(" EPSF-") > 0) { 83 while (lineLimit > 0 && line != null) { 85 lineLimit--; 86 if (line.startsWith("%%BoundingBox: ")) { 87 line = line.substring(15); 88 parseBox(line); 89 lineLimit = 0; 90 } 91 line = ir.readLine(); 92 } 93 } else { 94 System.err.println("Failed to interpret image: " + imageFn); 95 } 96 } catch (Exception e) { 97 System.err.println("Failed to load image: " + imageFn); 98 } 99 100 if (ir != null) { 101 try { 102 ir.close(); 103 } catch (Exception e) { 104 } 106 } 107 } 108 } 109 110 public int getWidth(int defaultWidth) { 111 if (width >= 0) { 112 return width; 113 } else { 114 return defaultWidth; 115 } 116 } 117 118 public int getDepth(int defaultDepth) { 119 if (depth >= 0) { 120 return depth; 121 } else { 122 return defaultDepth; 123 } 124 } 125 126 private void parseBox(String line) { 127 int [] corners = new int [4]; 128 int count = 0; 129 130 StringTokenizer st = new StringTokenizer (line); 131 while (count < 4 && st.hasMoreTokens()) { 132 try { 133 corners[count++] = Integer.parseInt(st.nextToken()); 134 } catch (Exception e) { 135 } 137 } 138 139 width = corners[2] - corners[0]; 140 depth = corners[3] - corners[1]; 141 } 142 143 public boolean imageUpdate(Image img, int infoflags, 144 int x, int y, int width, int height) { 145 if ((infoflags & ImageObserver.ERROR) == ImageObserver.ERROR) { 146 imageFailed = true; 147 return false; 148 } 149 150 int flags = ImageObserver.ALLBITS; 154 if ((infoflags & flags) == flags) { 155 return false; 156 } else { 157 return true; 158 } 159 } 160 } 161 | Popular Tags |