Java image resize, maintain aspect ratio

前端 未结 11 1490
盖世英雄少女心
盖世英雄少女心 2020-11-28 19:38

I have an image which I resize:

if((width != null) || (height != null))
{
    try{
        // scale image on disk
        BufferedImage originalImage = ImageI         


        
11条回答
  •  半阙折子戏
    2020-11-28 19:54

    I have found the selected answer to have problems with upscaling, and so I have made (yet) another version (which I have tested):

    public static Point scaleFit(Point src, Point bounds) {
      int newWidth = src.x;
      int newHeight = src.y;
      double boundsAspectRatio = bounds.y / (double) bounds.x;
      double srcAspectRatio = src.y / (double) src.x;
    
      // first check if we need to scale width
      if (boundsAspectRatio < srcAspectRatio) {
        // scale width to fit
        newWidth = bounds.x;
        //scale height to maintain aspect ratio
        newHeight = (newWidth * src.y) / src.x;
      } else {
        //scale height to fit instead
        newHeight = bounds.y;
        //scale width to maintain aspect ratio
        newWidth = (newHeight * src.x) / src.y;
      }
    
      return new Point(newWidth, newHeight);
    }
    

    Written in Android terminology :-)

    as for the tests:

    @Test public void scaleFit() throws Exception {
      final Point displaySize = new Point(1080, 1920);
      assertEquals(displaySize, Util.scaleFit(displaySize, displaySize));
      assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x / 2, displaySize.y / 2), displaySize));
      assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x * 2, displaySize.y * 2), displaySize));
      assertEquals(new Point(displaySize.x, displaySize.y * 2), Util.scaleFit(new Point(displaySize.x / 2, displaySize.y), displaySize));
      assertEquals(new Point(displaySize.x * 2, displaySize.y), Util.scaleFit(new Point(displaySize.x, displaySize.y / 2), displaySize));
      assertEquals(new Point(displaySize.x, displaySize.y * 3 / 2), Util.scaleFit(new Point(displaySize.x / 3, displaySize.y / 2), displaySize));
    }
    

提交回复
热议问题