Search code examples
javaswingawtsun

Java getting area of pixels and turning into an image - how can this be made more efficient?


I have some code which will grab an area of pixels on the screen and turn them into a BufferedImage object. The thing is - it is MASSIVELY slow, so I am looking for support in increasing its speed!

The code is as follows:

public BufferedImage getScreenPortion(Point topleft,Point bottomright){

    int width = bottomright.x - topleft.x;
    int height = bottomright.y - topleft.y;
    BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

    for(int p=0;p<height;p++){

    for(int i= 0;i<width;i++){

        Color pixel = robot.getPixelColor(topleft.x+i, topleft.y+p);
        bi.setRGB(i, p, pixel.getRGB());
        }
    }

    return bi;


}

and I am passing it : getScreenPortion(new Point(1081,824),new Point(1111,844)); which means I am trying to get an areas approximately 30x20 - yet it is taking in the region of 7 seconds which is horrendously slow!


Solution

  • Fixed it - I now instead use:

    Rectangle screenRect = new Rectangle(topleft.x, topleft.y, width, height);
    BufferedImage grid = robot.createScreenCapture(screenRect);