How to load an image in a Java console application? (without an applet)
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 whatev开发者_StackOverflower reason.
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();
}
}
}
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
Where do you want to draw it ? Seeing it that you need some output this could help, assuming bmps( but other formats are explained):
http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/Encode.doc.html
// Define the source and destination file names.
String inputFile = /images/FarmHouse.tif
String outputFile = /images/FarmHouse.bmp
// Load the input image.
RenderedOp src = JAI.create("fileload", inputFile);
// Encode the file as a BMP image.
FileOutputStream stream =
new FileOutputStream(outputFile);
JAI.create("encode", src, stream, BMP, null);
// Store the image in the BMP format.
JAI.create("filestore", src, outputFile, BMP, null);
Reads and writes a Bmp File.
精彩评论