Reputation: 3227
I want to read an image and print ARGB value of all pixels.
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(...);
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?
Upvotes: 0
Views: 1245
Reputation: 535
You can try without JavaFX, like this:
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);
}
Upvotes: 2