6

I'm looking for the fastest way to write pixels on javafx.scene.image.Image. Writing to BufferedImage's backing array is much faster. At least on the test image I made it took only ~20ms for BufferedImage, WritableImage on the other hand took ~100ms. I already tried SwingFXUtils but no luck.

Code for BufferedImage (faster):

BufferedImage bi = createCompatibleImage( width, height );
WritableRaster raster = bi.getRaster();
DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();

System.arraycopy( pixels, 0, dataBuffer.getData(), 0, pixels.length );

Code for WritableImage (slower):

WritableImage wi = new WritableImage( width, height );
PixelWriter pw = wi.getPixelWriter();
WritablePixelFormat<IntBuffer> pf = WritablePixelFormat.getIntArgbInstance();

pw.setPixels( 0, 0, width, height, pf, pixels, 0, width );

Maybe there's a way to write to WritableImage's backing array too?

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
Ezekiel Baniaga
  • 853
  • 1
  • 12
  • 26

1 Answers1

2

For the performance of the pixel writer it is absolutely crucial that you pick the right pixel format. You can check what the native pixel format is via

pw.getPixelFormat().getType()

On my Mac this is PixelFormat.Type.BYTE_BGRA_PRE. If your raw data conforms to this pixel format, then the transfer to the image should be pretty fast. Otherwise the pixel data has to be converted and that takes some time.

mipa
  • 10,369
  • 2
  • 16
  • 35
  • This doesn't answer the question. The Pixel format depends on the source image being used. If you don't use the the format that matches the source image format you will get an exception at runtime. – dreamwagon Nov 25 '15 at 19:18
  • 3
    I assumed that the source pixel format can be adapted so that the maximum transfer rate can be achieved. This is often the case when you create the pixel content yourself. – mipa Nov 25 '15 at 20:28
  • Just to confirm this, I switched form `getIntArgbPreInstance` to `getByteBgraPreInstance`, changed my pixel writing loops to match the format, and saw roughly 3x times performance improvement – asimes Aug 08 '19 at 23:52