Scale an image to fit your screen

We’re going to see how to scale an ImageIcon to fit to your screen. The important point here is to respect a ratio, the one of the ImageIcon.
So imagine somenone send You an image through an OutputStream (one of my previous topic 🙂 ) and You want to display it on your screen, but adapt it to your screen respecting a ratio. The harder thing here is to do math 🙂 So let’s go.

First, we’ll need two variables for the both scaled width and height :

int scaledWidth, scaledHeight;

Our ImageIcon is called myImage. We’re going to first retrieve its original size :

int originalWidth = myImage.getIconWidth();
int originalHeight = myImage.getIconHeight();

// Then calculate the ratio
float imageRatio = (int) (originalWidth / originalHeight);

Then, we’re doing the same but with your screen size :

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
float screenRatio = (float) (screenSize.width / screenSize.height);

Now we have to compare the both ratios and find the right size for our image 🙂

if(imageRatio <= screenRatio) {
// The scaled size is based on the height
scaledHeight = screenSize.height;
scaledWidth = (int) (scaledHeight * imageRatio);
} else {
// The scaled size is based on the width
scaledWidth = screenSize.width;
scaledHeight = (int) (scaledWidth / imageRatio);
}

Nice !! We just have to get a scaled image now. That’s easy :

myImage = new ImageIcon(myImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_FAST));

Now it’s done.
Enjoy 🙂