Advertisement
dig090

Image scale with padding

Feb 25th, 2013
921
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. /**
  2.  * Like {@link #scaleWithMax(BufferedImage, int, int)} but the resulting image will include the scaled
  3.  * image along with transparent (hopefully) background color as a filler to the sides or top/bottom
  4.  * depending on the source img size.
  5.  */
  6. public static BufferedImage scaleWithPadding(BufferedImage img, int newWidth, int newHeight) {
  7.     int currentWidth = img.getWidth();
  8.     int currentHeight = img.getHeight();
  9.  
  10.     int scaledWidth;
  11.     int scaledHeight;
  12.     if (currentWidth == 0 || currentHeight == 0
  13.             || (currentWidth == newWidth && currentHeight == newHeight)) {
  14.         return img;
  15.     } else if (currentWidth == currentHeight) {
  16.         scaledWidth = newWidth;
  17.         scaledHeight = newHeight;
  18.     } else if (currentWidth >= currentHeight) {
  19.         scaledWidth = newWidth;
  20.         double scale = (double) newWidth / (double) currentWidth;
  21.         scaledHeight = (int) Math.round(currentHeight * scale);
  22.     } else {
  23.         scaledHeight = newHeight;
  24.         double scale = (double) newHeight / (double) currentHeight;
  25.         scaledWidth = (int) Math.round(currentWidth * scale);
  26.     }
  27.  
  28.     int x = (newWidth - scaledWidth) / 2;
  29.     int y = (newHeight - scaledHeight) / 2;
  30.  
  31.     /*
  32.      * This is _very_ painful. I've tried a large number of different permutations here trying to
  33.          * get the white image background to be transparent without success. We've tried different
  34.          * fills, composite types, image types, etc.. I'm moving on now.
  35.      */
  36.     BufferedImage newImg = new BufferedImage(newWidth, newHeight, img.getType());
  37.     Graphics2D g = newImg.createGraphics();
  38.     g.setColor(Color.WHITE);
  39.     g.fillRect(0, 0, newWidth, newHeight);
  40.     g.drawImage(img, x, y, x + scaledWidth, y + scaledHeight, 0, 0, currentWidth, currentHeight,
  41.                     Color.WHITE, null);
  42.     g.dispose();
  43.  
  44.     return newImg;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement