log.debug("done");
return;
}
BufferObjectReader oin = new BufferObjectReader(getStdIn());
BufferObjectWriter oout = new BufferObjectWriter(getStdOut());
// handle parameters
int x = 0, y = 0, w = 0, h = 0, x2 = -1, y2 = -1;
String inType = IMG_TYPE;
String outType = null;
for (int i = 0; i < params.length; i++) {
String str = params[i];
if (str.equals("-x1")) {
x = Integer.parseInt(params[++i]);
} else if (str.equals("-y1")) {
y = Integer.parseInt(params[++i]);
} else if (str.equals("-x2")) {
x2 = Integer.parseInt(params[++i]);
} else if (str.equals("-y2")) {
y2 = Integer.parseInt(params[++i]);
} else if (str.equals("-in")) {
inType = params[++i];
if (!inType.equals(IMG_TYPE) && !inType.equals(OBJ_TYPE)) {
throwException("Invalid in type");
return;
}
} else if (str.equals("-out")) {
outType = params[++i];
if (!outType.equals(IMG_TYPE) && !outType.equals(OBJ_TYPE)) {
throwException("Invalid out type");
return;
}
} else {
throwException("There is an unknown parameter.");
return;
}
}
if (outType == null) {
outType = inType;
}
// read image
BufferedImage image = null;
if (inType.equals(IMG_TYPE)) {
BufferInputStream bis = new BufferInputStream(getStdIn());
image = ImageIO.read(bis);
bis.close();
} else { // OBJ_TYPE
Object obj = null;
if (oin.hasNext()) {
obj = oin.next();
}
oin.close();
try {
image = (BufferedImage) obj;
} catch (Exception e) {
throwException("" + e);
return;
}
}
if (image == null) {
throwException("IMAGE == NULL");
return;
}
// test for crop area size
int imgh = image.getHeight();
int imgw = image.getWidth();
if (x2 == -1) x2 = imgw;
if (y2 == -1) y2 = imgh;
if (x < 0) x = 0;
if (y < 0) y = 0;
w = x2 - x;
h = y2 - y;
if (x > imgw) x = imgw;
if (y > imgh) y = imgh;
if (x + w > imgw) w = imgw - x;
if (y + h > imgh) h = imgh - y;
// make new image
BufferedImage newImage = new BufferedImage(w, h, image.getType());
newImage.setData(image.getData(new Rectangle(x, y, w, h)).createTranslatedChild(0, 0));
// write new image to stream
if (outType.equals(IMG_TYPE)) {
BufferOutputStream bos = new BufferOutputStream(getStdOut());
ImageIO.write(newImage, "jpg", bos);
bos.close();
} else { // OBJ_TYPE
oout.writeObject(newImage);
oout.close();
}
log.debug("done");
}