簡體   English   中英

如何在Java控制台應用程序中加載圖像? (沒有小程序)

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

我正在創建一個輸出一系列圖像文件的Java控制台應用程序,我想繪制一個圖像文件作為輸出的一部分。 getImage似乎不起作用,它需要Toolkit或其他東西。

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

有任何想法嗎?

編輯:程序不顯示圖像,它生成它們並將它們保存到一系列文件中。 我想出了如何保存圖像,繪制基本幾何圖形,但不管圖像是出於何種原因。

處理不同圖像格式的另一種方法是ImageIO類。 以下示例將jpg轉換為png並繪制十字。

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();
     }
    }
}

如果您實際上並沒有嘗試繪制圖像,只是嘗試使用awt類,則需要通過設置java.awt.headless系統屬性來告訴awt以無頭模式運行。 您可以在加載awt之前在程序中執行此操作:

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

或者在運行程序時在命令行上設置屬性:

java -Djava.awt.headless=true Program

你想在哪里畫畫? 看到你需要一些輸出,這可能有所幫助,假設bmps(但解釋了其他格式):

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);

讀取和寫入Bmp文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM