Search code examples
javamacoslwjglbufferedimage

BufferedImage causes a program freeze on MacOs but not on Windows


I'm using a piece of code to grab a screenshot of my application screen for a group project. On my Macbook Pro the code freezes the screen whereas on my teammates's PC's (all Windows) it runs just fine and exports a .png file in their root dir.

The code

public void screenShot(){
    //Creating an rbg array of total pixels
    int[] pixels = new int[WIDTH * HEIGHT];
    int bindex;
    // allocate space for RBG pixels
    ByteBuffer fb = ByteBuffer.allocateDirect(WIDTH * HEIGHT * 3);

    // grab a copy of the current frame contents as RGB
    glReadPixels(0, 0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, fb);

    // convert RGB data in ByteBuffer to integer array
    for (int i=0; i < pixels.length; i++) {
        bindex = i * 3;
        pixels[i] =
                ((fb.get(bindex) << 16))  +
                        ((fb.get(bindex+1) << 8))  +
                        ((fb.get(bindex+2) << 0));
    }
    //Allocate colored pixel to buffered Image
    BufferedImage imageIn = null;
    try{
        //THIS LINE 
        imageIn = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
        //THIS LINE ^^^^^ 
        imageIn.setRGB(0, 0, WIDTH, HEIGHT, pixels, 0 , WIDTH);
    } catch (Exception e) {
        e.printStackTrace();
    }

The problem

When debugging I can see that when stepping in at this line

imageIn = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);

the debugger doesn't go to the BufferedImage constructor but to GLFWKeyCallbackI.callback() and after that to GLFWCursorEnterCallbackI.callback(). After this it stops altogether.

What I tried

In my main class above all the rest of the code making a buffered Image as such:

BufferedImage imageIn = new BufferedImage(100,100,BufferedImage.TYPE_INT_RGB);

It also freezes the simulation but it does seems to actually execute the line.


I'm not sure what else I could try, I saw a few other posts ranging between 2005 and today asking similar Mac questions without an answer.


Solution

  • I delved a bit deeper and discovered the issue. As mentioned in a comment here if I provide this VM option "-Djava.awt.headless=true" it seems to fix the issue.