Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get aspect ratio of an Image in java?

    • 0
    • 3
    • 1
    • 4
    • 1
    • 0
    • 0
    • 0
    • 3.70k
    Comment on it

    Sometimes we need to get aspect ratio for an image in Java to fulfil our requirement. You can use the below code to get aspect ratio for an image in Java very easily:

    1. Define the dimension boundary of which you want resized image as below ( here you will define the height/width to get aspect ration of the image)
    2. Dimension boundary = new Dimension(350, 350); // here you can provide custom height/width
    3. Get the Scaled dimension of the image you want to resize. In this method you will pass Original imageSize and boundary.
    /**
     * This method will provide aspect ratio of an image
     * @param imgSize
     * @param boundary
     * @return
     */
    public static Dimension getScaledDimension(BufferedImage imgSize, Dimension boundary) {
    
        int original_width = imgSize.getWidth();
        int original_height = imgSize.getHeight();
        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;
        }
    
        return new Dimension(new_width, new_height);
    }

    Hope this will help you.Good Luck :)

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: