Java image resize, maintain aspect ratio

前端 未结 11 1471
盖世英雄少女心
盖世英雄少女心 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 20:05

    Just add one more block to Ozzy's code so the thing looks like this:

    public static Dimension getScaledDimension(Dimension imgSize,Dimension boundary) {
    
        int original_width = imgSize.width;
        int original_height = imgSize.height;
        int bound_width = boundary.width;
        int bound_height = boundary.height;
        int new_width = original_width;
        int new_height = original_height;
    
        // first check if we need to scale width
        if (original_width > bound_width) {
            //scale width to fit
            new_width = bound_width;
            //scale height to maintain aspect ratio
            new_height = (new_width * original_height) / original_width;
        }
    
        // then check if we need to scale even with the new height
        if (new_height > bound_height) {
            //scale height to fit instead
            new_height = bound_height;
            //scale width to maintain aspect ratio
            new_width = (new_height * original_width) / original_height;
        }
        // upscale if original is smaller
        if (original_width < bound_width) {
            //scale width to fit
            new_width = bound_width;
            //scale height to maintain aspect ratio
            new_height = (new_width * original_height) / original_width;
        }
    
        return new Dimension(new_width, new_height);
    }
    

提交回复
热议问题