import java.awt.*;
import java.awt.print.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
 * A "Printable" version of an Image
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class PrintableImage implements Printable
{
    private double        height, width;
    private Image         image;
    
    /**
     * Explicit Value Constructor
     *
     * @param file   The name of the file containing the image
     */
    public PrintableImage(String file) throws IOException
    {
       image   = ImageIO.read(new File(file));
       width   = image.getWidth(null);
       height  = image.getHeight(null);
    }


    /**
     * Print the image (required by Printable)
     *
     * @param g      The rendering engine
     * @param format The format of the page
     * @param page   The page number
     */
    public int print(Graphics g, PageFormat format, int page)
    {
       double        h, w;
       Graphics2D    g2;
       int           status, x, y;


       g2 = (Graphics2D)g;
       status = Printable.NO_SUCH_PAGE;
       if (page == 0) 
       {
          h = format.getHeight();
          w = format.getWidth(); 

          // Calculatethe position that centers the image
          x = (int)(w/2.0  - width/2.0);
          y = (int)(h/2.0 - height/2.0);

          // Draw the image (as with any rendering engine)
          g2.drawImage(image, x, y, null);

          // Inform the caller that a page has been drawn
          status = Printable.PAGE_EXISTS;
       }
       return status;
    }
}
