Java Program to Load and Display an 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.

advertisement

When the Applet is Executed :

This image is available at the present working directory as “logo.jpeg”
java-applet-load-image-logo

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.

advertisement
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:

>>>javac Load_Image.java
>>>appletviewer Load_Image.java
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.

advertisement
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.
java-program-load-image

Sanfoundry Global Education & Learning Series – Java Programs.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn