Java - 如何为 img.getScaledInstance( ); 自动设置宽度?
Java - how to auto set width for img.getScaledInstance( );?
如果图像太大,我想调整它的大小,但我希望它保持纵横比,我怎样才能定义它的高度并让它自动获得它的宽度?
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);
你应该做一些maths.find高度和旧高度的比例然后找到新的宽度
double Width=(200/(double)image2.getIconHeight())*image2.getIconWidth();
然后你可以设置宽度
Image newimg = img.getScaledInstance( Width, 200, java.awt.Image.SCALE_SMOOTH ) ;
复制自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.
所以你可以这样做,
img.getScaledInstance(-1, 200, java.awt.Image.SCALE_SMOOTH ) ;
如果图像太大,我想调整它的大小,但我希望它保持纵横比,我怎样才能定义它的高度并让它自动获得它的宽度?
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);
你应该做一些maths.find高度和旧高度的比例然后找到新的宽度
double Width=(200/(double)image2.getIconHeight())*image2.getIconWidth();
然后你可以设置宽度
Image newimg = img.getScaledInstance( Width, 200, java.awt.Image.SCALE_SMOOTH ) ;
复制自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.
所以你可以这样做,
img.getScaledInstance(-1, 200, java.awt.Image.SCALE_SMOOTH ) ;