简体   繁体   中英

Image resize - maintain aspect ratio

How could I resize an image and still keep it's aspect ratio?

This is the method that I use :

private static BufferedImage resizeImage(BufferedImage originalImage,
            int type) {
        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
                type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();

        return resizedImage;
    }

The type variable :

BufferedImage original = ImageIO.read(new File(imagePath));
int type = original.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                    : original.getType();

The problem is that some images are correctly resized but others lose their aspect ratio because of the IMG_WIDTH and IMG_HEIGHT.

Is there a way to get the original image dimensions and then apply some kind of proportion resize to maintain the aspect ratio of the resized image?

Why don't you use originalImage.getWidth() and originalImage.getHeight() ? Then you can easily calculate aspect ratio. Don't forget that int/int = int, so you need to do

double ratio = 1.0 * originalImage.getWidth() / originalImage.getHeight();

or 

double ratio = (double) originalImage.getWidth() / originalImage.getHeight();

Regarding the additional math, you can calculate

int height = (int) IMG_WIDTH/ratio;

int width = (int) IMG_HEIGHT*ratio;

Then see which one fits your needs better and resize to (IMG_WIDTH, height) or (width, IMG_HEIGHT)

To get the image size, see getWidth() / getHeight() . The rest is just some relatively simple math.

Presuming the IMG_WIDTH & IMG_HEIGHT represent the largest size desired:

  • Find which is going to hit the limit first.
  • Calculate the ratio between the natural size and that maximum size.
  • Multiply the other image dimension by the same ratio.

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