Kent Ong
Kent Ong

Reputation: 53

Java - how to auto set width for img.getScaledInstance( );?

I wanted to resize a image if it is too large, but i want it to keep it's aspect ratio, how can i just define it's height and let it automatically get it's width?

ImageIcon image2 = new ImageIcon(image);

//Check if image size is more than 200

if(!checking){
    Image img = image2.getImage() ;  
    Image newimg = img.getScaledInstance( "What to put here?", 200,  java.awt.Image.SCALE_SMOOTH ) ;  
    image2 = new ImageIcon( newimg );
}   

JButton newimage = new JButton(image2);

Upvotes: 0

Views: 884

Answers (2)

Codebender
Codebender

Reputation: 14471

Copied from Javadocs,

If either width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions. If both width and height are negative, then the original image dimensions are used.

So you could just do,

img.getScaledInstance(-1, 200,  java.awt.Image.SCALE_SMOOTH ) ;

Upvotes: 3

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9872

you should do some maths.find the ratio of height and old height then find new width

double Width=(200/(double)image2.getIconHeight())*image2.getIconWidth();

then you can set width

Image newimg = img.getScaledInstance( Width, 200,  java.awt.Image.SCALE_SMOOTH ) ;  

Upvotes: 3

Related Questions