title: How to fit a portrait image in landscape orientation in JAVA (with border) keeping the aspect ratio
body: <p>my landscape images are already as i want them to be at the output, but for the portrait my code does not work, i know i have something to do when the source height > source width but I don't know exactly what. I need help ! </p>
  
  <p>Here is my code :</p>
  
  <pre><code>public static BufferedImage resize(BufferedImage img, int newW, int newH){ 
      int w = img.getWidth();  
      int h = img.getHeight();
  
      double thumbRatio = (double) newW / (double) newH;
      int imageWidth = img.getWidth(null);
      int imageHeight = img.getHeight(null);
      double aspectRatio = (double) imageWidth / (double) imageHeight;
  
      if (thumbRatio &lt; aspectRatio) {
          newH = (int) (newW / aspectRatio);
      }
      else {
          newW = (int) (newH * aspectRatio);
      }
  
      //if (w &gt; 1024 || h &gt; 768) {
      BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());
      Graphics2D g = dimg.createGraphics();  
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  
      g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
      g.dispose();
  
      return dimg;
      //}else return img;
  }  
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Hc0tO.png" rel="nofollow noreferrer">this is the expected output</a></p>