private byte[] cropAndCompressImage(int x, int y, int w, int h, BufferedImage image, int targetW, int targetH) throws Exception{ if (w == -1 && h == -1 && image != null) { // use full image w = image.getWidth(); h = image.getHeight(); } if (x < 0 || y < 0 || w <= 0 || h <= 0 || image == null) { // error } w = Math.min(x+w, image.getWidth()) - x; h = Math.min(y+h, image.getHeight()) - y; try { BufferedImage cropedImage = image.getSubimage(x, y, w, h);
// do image compression int type = image.getType() == 0 ? BufferedImage.TRANSLUCENT : image.getType(); BufferedImage compressedImage = new BufferedImage(targetW, targetH, type); Graphics2D graph = compressedImage.createGraphics(); graph.drawImage(cropedImage, 0, 0, targetW, targetH, null); graph.dispose();
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ImageIO.write(compressedImage, "jpg", bytes);