有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

awt如何在Java控制台应用程序中加载映像?(不带小程序)

我正在制作一个Java控制台应用程序,输出一系列图像文件,我想画一个图像文件作为输出的一部分。但是getImage似乎不起作用,它需要工具箱之类的东西

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

有什么想法吗

编辑:程序不显示图像,而是生成图像并将其保存到一系列文件中。我知道了如何保存图像,并绘制了基本的几何图形,但无论出于何种原因,都无法绘制图像


共 (3) 个答案

  1. # 1 楼答案

    使用不同图像格式的另一种方法是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();
         }
        }
    }
    
  2. # 2 楼答案

    你想在哪里画?考虑到您需要一些输出,假设BMP(但解释了其他格式),这可能会有所帮助:

    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文件

  3. # 3 楼答案

    如果您实际上没有尝试绘制图像,而只是尝试使用awt类,则需要通过设置java.awt.headless系统属性来告诉awt以无头模式运行。在加载awt之前,您可以在程序中执行以下操作:

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

    或者在运行程序时在命令行上设置属性:

    java -Djava.awt.headless=true Program