简体   繁体   中英

Infinite while loop in Java application

In my Java application i am trying to resize an image until it fits a required dimension but still keeping its original scale.

the following method is used for resizing the image.

public BufferedImage ImageScaler(BufferedImage image){
    scaledWidth = (int) image.getWidth() / SCALE_FACTOR * 100;
    scaledHeight = (int) image.getHeight() / SCALE_FACTOR * 100;
    scaledImage = resize(image, scaledHeight, scaledWidth);

    while(scaledHeight > 150){
        scaledHeight = scaledImage.getHeight();
        scaledWidth = scaledImage.getWidth();
        scaledImage = resize(image, scaledHeight, scaledWidth);
        scaledHeight = scaledImage.getHeight();
        scaledWidth = scaledImage.getWidth();
    }

    return scaledImage;
}

the while loop goes into an infinte loop. please help.

resize method.

 private static BufferedImage resize(BufferedImage img, int height, int width) {
    java.awt.Image tmp = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
    BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = resized.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    return resized;
}

Your code doesn't actually change anything. Suppose that when it goes into the loop, the width and height are both 200; the first two lines merely set scaledHeight and scaledWidth to 200, the third edits the image to conform to said variables, and then the fourth and fifth line set it to.. Exactly the same dimensions again. If after the initial resizing before the loop scaledHeight doesn't reach 150, it never will.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM