Resize image while keeping aspect ratio in Java

后端 未结 7 887
清歌不尽
清歌不尽 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:06

    For starters - take a look at line 2. Shouldnt that be getHeight()?

    You dont want a while loop for the resizing, you want to find out the resizing ratio, which is a simple bit of math.

    (width / height) = (new_width / new_height)
    

    If you know one of the 'new' sizes, the other can be found via multiplication

    new_height * (width / height) = new_width
    

    You can also use the lazy method provided by BufferedImage's superclass Image, getScaledInstance() - using -1 for either width or height will maintain aspect ratio

    ex:
    scaledPic = picture.getScaledInstance(new_width, -1, Image.SCALE_FAST);

提交回复
热议问题