Java Program to Display Image using Applet

This is a Java Program to Load and Display an Image Using Applet

Problem Description

We have to write a program in Java such that it loads and displays an image using applet.

Expected Input and Output

For loading and displaying image, we can have the following set of input and output.

When the Applet is Executed :

This image is available at the present working directory as “logo.jpeg”

When the applet is executed,
it is expected that the image is displayed in the frame.
Problem Solution

1. Use method getImage to load the image.
2. Use method drawImage to draw the image.

Program/Source Code

Here is source code of the Java Program to load and display image using applet. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.

  1. /*Java Applet to Load and Display Image*/
  2. import java.awt.*;
  3. import java.applet.*;
  4. public class Load_Image extends Applet
  5. { 
  6.     Image image;
  7.     //Fucntion to Load the image
  8.     public void init()
  9.     {
  10. 	image=getImage(getCodeBase(),"logo.jpeg");
  11.     }
  12.     //Function to draw the image
  13.     public void paint(Graphics g)
  14.     {
  15. 	g.drawImage(image,0,0,this);
  16.     }
  17. }
  18. /*
  19. <applet code = Load_Image.class width=500 height=500>
  20. </applet>
  21. */

To execute the applet use the following commands:

Program Explanation

1. The method getImage(getCodeBase(),image file name) is used to get the image.
2. The method drawImage(image file,x,y,component) is used to draw the image starting from the x and y co-ordinates in the component specified.

Runtime Test Cases

Here’s the run time test cases to Load and Display Image using Applet.

Test case 1 – To Load and Display Image.

Sanfoundry Global Education & Learning Series – Java Programs.


If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.