Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an image in a Java console application? (without an applet)

Tags:

java

awt

I'm making a Java console application that outputs a series of image files, and I want to draw an image file as part of the output. getImage doesn't seem to work though, it needs Toolkit or something.

Image cover = getImage("cover.png");

Any ideas?

Edit: The program doesn't display images, it generates them and saves them into a series of files. I figured out how to save the images, and drawing basic geometry works, but not images for whatever reason.

like image 255
nkorth Avatar asked Jun 01 '26 12:06

nkorth


2 Answers

Another way of working with different image-formats is the ImageIO class. The following example converts a jpg into png and draws a cross.

public class ImageReaderExample {

    public static void main(String[] args) {
     try{
          BufferedImage image = ImageIO.read(new File("/tmp/input.jpg"));

          image.getGraphics().drawLine(1, 1, image.getWidth()-1, image.getHeight()-1);
          image.getGraphics().drawLine(1, image.getHeight()-1, image.getWidth()-1, 1);

          ImageIO.write(image, "png", new File("/tmp/output.png"));
     }
     catch (IOException e){
         e.printStackTrace();
     }
    }
}
like image 131
tfk Avatar answered Jun 03 '26 00:06

tfk


If you're not actually trying to draw the image, but just trying to use the awt classes, you need to tell awt to run in headless mode by setting the java.awt.headless system property. You can either do this in your program, before awt gets loaded:

System.setProperty("java.awt.headless", "true"); 

or by setting the property on the command line when you run your program:

java -Djava.awt.headless=true Program
like image 28
highlycaffeinated Avatar answered Jun 03 '26 01:06

highlycaffeinated