 |
|
|
ImageViewer.java
|
/*
* Author: Havard Rast Blok
* E-mail:
* Web : www.rememberjava.com
*/
import java.awt.*;
import javax.swing.*;
/*
* Application to view and and scale an image.
*/
public class ImageViewer extends JFrame
{
private Image img;
public ImageViewer( String fName )
{
super("My ImageViewer and scaler");
Toolkit tk;
tk = Toolkit.getDefaultToolkit();
img = tk.createImage(fName);
setSize(400, 500);
show();
}
public void paint( Graphics g )
{
//use float variables to avoid integer devisions
float imgWidth, imgHeight;
float scrWidth, scrHeight;
float newWidth, newHeight;
float imgRatio, scrRatio;
//get image and frame size
imgWidth = img.getWidth(this);
imgHeight = img.getHeight(this);
scrWidth = getWidth();
scrHeight = getHeight();
//check that images was loaded
if( imgWidth > 0 && imgHeight > 0 )
{
//calculate aspect ratio
imgRatio = imgHeight/imgWidth;
scrRatio = scrHeight/scrWidth;
//the new size
if( imgRatio < scrRatio )
{
newWidth = scrWidth;
newHeight = imgHeight * (newWidth/imgWidth);
}
else
{
newHeight = scrHeight;
newWidth = imgWidth * (newHeight/imgHeight);
}
System.out.println("scrRatio="+scrRatio+", imgRatio="+imgRatio+", new Ratio="+(newHeight/newWidth));
g.drawImage(img, 0, 0, (int)newWidth, (int)newHeight, this);
}
}
public static void main( String [] args)
{
new ImageViewer( args[0] );
}
}
|
|
|
 |