Java image resize, maintain aspect ratio

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

    Translated from here:

    Dimension getScaledDimension(Dimension imageSize, Dimension boundary) {
    
        double widthRatio = boundary.getWidth() / imageSize.getWidth();
        double heightRatio = boundary.getHeight() / imageSize.getHeight();
        double ratio = Math.min(widthRatio, heightRatio);
    
        return new Dimension((int) (imageSize.width  * ratio),
                             (int) (imageSize.height * ratio));
    }
    

    You can also use imgscalr to resize images while maintaining aspect ratio:

    BufferedImage resizeMe = ImageIO.read(new File("orig.jpg"));
    Dimension newMaxSize = new Dimension(255, 255);
    BufferedImage resizedImg = Scalr.resize(resizeMe, Method.QUALITY,
                                            newMaxSize.width, newMaxSize.height);
    

提交回复
热议问题