1 7 8 package java.awt.image; 9 10 import java.awt.image.ImageConsumer ; 11 import java.awt.image.ColorModel ; 12 import java.util.Hashtable ; 13 import java.awt.Rectangle ; 14 15 29 public class CropImageFilter extends ImageFilter { 30 int cropX; 31 int cropY; 32 int cropW; 33 int cropH; 34 35 44 public CropImageFilter(int x, int y, int w, int h) { 45 cropX = x; 46 cropY = y; 47 cropW = w; 48 cropH = h; 49 } 50 51 64 public void setProperties(Hashtable <?,?> props) { 65 Hashtable <Object ,Object > p = (Hashtable <Object ,Object >)props.clone(); 66 p.put("croprect", new Rectangle (cropX, cropY, cropW, cropH)); 67 super.setProperties(p); 68 } 69 70 82 public void setDimensions(int w, int h) { 83 consumer.setDimensions(cropW, cropH); 84 } 85 86 98 public void setPixels(int x, int y, int w, int h, 99 ColorModel model, byte pixels[], int off, 100 int scansize) { 101 int x1 = x; 102 if (x1 < cropX) { 103 x1 = cropX; 104 } 105 int x2 = addWithoutOverflow(x, w); 106 if (x2 > cropX + cropW) { 107 x2 = cropX + cropW; 108 } 109 int y1 = y; 110 if (y1 < cropY) { 111 y1 = cropY; 112 } 113 114 int y2 = addWithoutOverflow(y, h); 115 if (y2 > cropY + cropH) { 116 y2 = cropY + cropH; 117 } 118 if (x1 >= x2 || y1 >= y2) { 119 return; 120 } 121 consumer.setPixels(x1 - cropX, y1 - cropY, (x2 - x1), (y2 - y1), 122 model, pixels, 123 off + (y1 - y) * scansize + (x1 - x), scansize); 124 } 125 126 138 public void setPixels(int x, int y, int w, int h, 139 ColorModel model, int pixels[], int off, 140 int scansize) { 141 int x1 = x; 142 if (x1 < cropX) { 143 x1 = cropX; 144 } 145 int x2 = addWithoutOverflow(x, w); 146 if (x2 > cropX + cropW) { 147 x2 = cropX + cropW; 148 } 149 int y1 = y; 150 if (y1 < cropY) { 151 y1 = cropY; 152 } 153 154 int y2 = addWithoutOverflow(y, h); 155 if (y2 > cropY + cropH) { 156 y2 = cropY + cropH; 157 } 158 if (x1 >= x2 || y1 >= y2) { 159 return; 160 } 161 consumer.setPixels(x1 - cropX, y1 - cropY, (x2 - x1), (y2 - y1), 162 model, pixels, 163 off + (y1 - y) * scansize + (x1 - x), scansize); 164 } 165 166 private int addWithoutOverflow(int x, int w) { 168 int x2 = x + w; 169 if ( x > 0 && w > 0 && x2 < 0 ) { 170 x2 = Integer.MAX_VALUE; 171 } else if( x < 0 && w < 0 && x2 > 0 ) { 172 x2 = Integer.MIN_VALUE; 173 } 174 return x2; 175 } 176 } 177 | Popular Tags |