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 :