I'm trying to maintain aspect ratio by calculating width percentage and height percentage of the original image and then set the new height and new width based on percentages but there is something wrong in my code :
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
public class Test extends JFrame {
private JPanel principalPanel;
private BufferedImage image;
public Test() {
setSize(600,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
URL url = new
URL("https://boygeniusreport.files.wordpress.com/2017/04/earth.jpg");
image = ImageIO.read(url);
} catch (Exception e) {
System.out.println("Problem loading image");
e.printStackTrace();
}
principalPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = image.getWidth();
int height = image.getHeight();
int wPercentage = (width*100)/(width+height);
int hPercentage = (height*100)/(width+height);
int w = (width+((getHeight()-height)*wPercentage)/hPercentage);
int h = (height+((getWidth()-width)*hPercentage)/wPercentage);
g.drawImage(image,0,0,w,h,this);
}
};
setContentPane(principalPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
}