Start Search Contents Index Links About
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 ImageViewerString fName )
  {
    super("My ImageViewer and scaler");

    Toolkit tk;
    
    tk = Toolkit.getDefaultToolkit();
    img = tk.createImage(fName);

    setSize(400500);
    show();
  }
  
  public void paintGraphics 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
    ifimgWidth > && imgHeight > )
    {
      //calculate aspect ratio
      imgRatio = imgHeight/imgWidth;
      scrRatio = scrHeight/scrWidth;
      
      //the new size
      ifimgRatio < 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, 00(int)newWidth, (int)newHeight, this);
    }
  }

  public static void mainString [] args)
  {
    new ImageViewerargs[0] )
  }

}


site: Håvard Rast Blok
mail:
updated: 27 July 2007