Resize image while keeping aspect ratio in Java

后端 未结 7 889
清歌不尽
清歌不尽 2020-12-13 10:58

im trying to resize bufferdImage in memory in java but to keep the aspect ratio of the image im have something like this but this is not good

int w = pictu         


        
7条回答
  •  孤城傲影
    2020-12-13 11:18

    If width, height of source and target are known, use following function to determine scale of the image.

    private double determineImageScale(int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) {
    
    double scalex = (double) targetWidth / sourceWidth;
    double scaley = (double) targetHeight / sourceHeight;
    return Math.min(scalex, scaley);
    

    }

    Then use this scale to scale up/down the image using following code

    Image scaledImage = sourceBufferedImage.getScaledInstance((int) (width * scale), (int) (height * scale), Image.SCALE_SMOOTH);
    

提交回复
热议问题