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🙂

2 Responses to Scale an image to fit your screen

  1. Chris Markle says:

    Thanks for this solution…

  2. Someoneelse says:

    if myImage is an ImageIcon the final line should be:
    myImage = new ImageIcon(myImage.getImage().getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_FAST));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: