简体   繁体   English

使用JavaFx图像读取图像像素

[英]Reading pixels of image using JavaFx Image

I want to read an image and print ARGB value of all pixels. 我想读取图像并打印所有像素的ARGB值。

This is how I try to achieve that: 这是我尝试实现的方法:

public static void main(String[] ar){

    Image image = new Image("file:///C:/Users/PC2/Desktop/duke_44x80.png"); //ERROR HERE
    ImageView imageView = new ImageView();
    imageView.setImage(image);

    PixelReader pixelReader = image.getPixelReader();

    for(int x = 0; x < image.getWidth(); ++x){
        for(int y = 0; y < image.getHeight(); ++y){

            System.out.print(pixelReader.getArgb(x, y) + ", ");

        }
        System.out.println();
    }

}

But when I try to run it, I get an error at line Image image = new Image(...); 但是当我尝试运行它时,在Image image = new Image(...);行出现错误Image image = new Image(...);

Exception in thread "main" java.lang.RuntimeException: Internal graphics not initialized yet
    at javafx.graphics/com.sun.glass.ui.Screen.getScreens(Screen.java:70)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.getScreens(QuantumToolkit.java:699)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.getMaxRenderScale(QuantumToolkit.java:726)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.loadImage(QuantumToolkit.java:735)
    at javafx.graphics/javafx.scene.image.Image.loadImage(Image.java:1052)
    at javafx.graphics/javafx.scene.image.Image.initialize(Image.java:802)
    at javafx.graphics/javafx.scene.image.Image.<init>(Image.java:618)
    at test.core.MainCore.main(MainCore.java:11)

How to fix this error? 如何解决这个错误?

You can try without JavaFX, like this: 您可以尝试不使用JavaFX,如下所示:

Path path = Paths.get("C:/Users/PC2/Desktop/duke_44x80.png");
        try(InputStream is = Files.newInputStream(path)) {
            BufferedImage bi = ImageIO.read(is); // Use ImageIO to create a BufferedImage
            int w = bi.getWidth();
            int h = bi.getHeight();
            for(int i = 0; i < h; i++) {
                for(int j = 0; j < w; j++) {
                    Color myColor = new Color(bi.getRGB(j, i)); // bi.getRGB returns an integer like -14350844, representing the specific color. use Color class to get the individual colors with: myColor.getBlue()...
                    System.out.print(myColor + ", ");
                }
                System.out.println();
            }

        }catch(IOException e) {
            System.out.println(e);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM