code: public static BufferedImage scaleImage( BufferedImage image, int newSize ) throws Exception {
  
          int imageWidth = image.getWidth();
          int imageHeight = image.getHeight();
          int width;
          int height;
          if (imageWidth > imageHeight) {
              width = newSize;
              height = imageHeight * width / imageWidth;
          } else {
              height = newSize;
              width = height * imageWidth / imageHeight;
          }
  
          BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          Graphics2D g = resizedImage.createGraphics();
          g.drawImage(image, 0, 0, width, height, null);
          g.dispose();
  
          return resizedImage;
      }
docs: Scale an image to a given size maintaining the ratio.
  
  @param image the image to scale.
  @param newSize the size of the new image (it will be used for the longer side).
  @return the scaled image.
  @throws Exception