Search code examples
javabitmappixelbufferedimageraster

What is the best way to load-manipulate-update picture/pixels?


There's BufferedImage (btw, is it the best way to store and edit frame's graphics?) and function that does some editing to this image.

My current approach:

 //usage: 
image.setData(update(image.getRaster()));


public Raster update(WritableRaster raster) {
    int[] pixels = new int[raster.getWidth() * raster.getHeight()];
    raster.getDataElements(0, 0, w, h, pixels); // raster to int[]
  //pixels array operations      
    raster.setDataElements(0, 0, w, h, pixels); // int[] to raster
    return raster;
}

Sending raster seems to be a bottleneck of this approach but what are the other options?


Solution

  • You can write efficiently into any pixel in the image by storing color values directly in the raster. The most performant way I've found to dynamically manipulate images this way is like this:

    BufferedImage image = new BufferedImage(inputWidth, inputHeight, BufferedImage.TYPE_INT_ARGB);
            int[] rgbRaster = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
    
            for(int i = 0; i < inputHeight; i++) {
                for(int j = 0; j < inputWidth; j++) {
                    int index = (inputWidth  * i) + j;
                    rgbRaster[index] = SOME_ARG_VALUE;
                    }
                }
            }
    

    Of course you don't have to recreate the image or raster array over and over, just create them once, and write into the array when you want to. Pretty fast, and pretty easy.