public final static byte[] resizeImage(byte[] imageBytes, int maxDim)
throws IOException {
ImageIcon inImage = new ImageIcon(imageBytes); // Determine the scale.
double scale = (double) maxDim / (double) inImage.getIconHeight(); if (inImage.getIconWidth() > inImage.getIconHeight()) {
scale = (double) maxDim / (double) inImage.getIconWidth();
} // Determine size of new image.
// One of them hould equal maxDim.
int scaledW = (int) (scale * inImage.getIconWidth());
int scaledH = (int) (scale * inImage.getIconHeight()); // Create an image buffer in which to paint on.
BufferedImage outImage = new BufferedImage(scaledW, scaledH,
BufferedImage.TYPE_INT_RGB); // Set the scale.
AffineTransform tx = new AffineTransform(); // If the image is smaller than the desired image size,
// don't bother scaling.
if (scale < 1.0d) {
tx.scale(scale, scale);
} // Paint image.
Graphics2D g2d = outImage.createGraphics();
g2d.drawImage(inImage.getImage(), tx, null);
g2d.dispose(); // JPEG-encode the image and write the response
ByteArrayOutputStream os = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage); return os.toByteArray();
}