// DrawImageFromFile.java // Place an image named "sampleImage.jpg" in the same directory as // this file, then compile and run this code to display the image. import java.awt.*; import javax.swing.*; public class DrawImageFromFile extends JApplet { public static Image getImageFromFile(String filename) { return new ImageIcon(filename).getImage(); } // Load the image only once -- so make it static private static Image sampleImage = getImageFromFile("sampleImage.jpg"); public void paint(Graphics page) { // get the dimensions of the draw area int width = this.getWidth(); int height = this.getHeight(); // clear the background page.setColor(new Color(120,120,50)); page.fillRect(0,0,width,height); // center the image in the window int imageWidth = sampleImage.getWidth(null); int imageHeight = sampleImage.getHeight(null); page.drawImage(sampleImage, (width - imageWidth)/2,(height - imageHeight)/2, null); // now draw a version of the image at (0,0) and scaled to be smaller int scaledWidth = imageWidth / 5; int scaledHeight = imageHeight / 5; page.drawImage(sampleImage,0,0,scaledWidth,scaledHeight,null); } public void init() { setBackground(Color.white); } //////////////////////////////////////////// // Main (applet wrapper) //////////////////////////////////////////// public static void main(String[] args) { DrawImageFromFile applet = new DrawImageFromFile(); applet.init(); final JFrame frame = new JFrame("DrawImageFromFile"); frame.getContentPane().add(applet); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setSize(600,600); frame.show(); } }