Loading an Image from a file

In this tutorial we are going to show you how to draw on an Image. This is quite useful when you want to further customize the graphics of your application, if you are not pleased with the original Image.

In short in order to Draw on a Buffered Image one should take the following steps:

  • Load an image from a source usingToolkit.getDefaultToolkit().getImage method.
  • Use an ImageObserver to monitor the loading of the image. When the image is fully load the user will be notified.


Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ImageObserver;

public class LoadImage {

  static boolean imageLoaded = false;

  public static void main(String[] args) {

    // The ImageObserver implementation to observe loading of the image
    ImageObserver myImageObserver = new ImageObserver() {

  public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {

    if ((flags & ALLBITS) != 0) {

    imageLoaded = true;

System.out.println("Image loading finished!");

return false;


    return true;



// The image URL - change to where your image file is located!

String imageURL = "image.png";


  * This call returns immediately and pixels are loaded in the background

  * We use an ImageObserver to be notified when the loading of the image 

  * is complete


Image image = Toolkit.getDefaultToolkit().getImage(imageURL);


while(!imageLoaded) {





This was an example on loading an image from a File.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button