Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working in a BufferedImage's int[] pixels array

When working with BufferedImage using the setRGB and getRGB methods, I noticed two things:

  1. the setRGB and getRGB methods can be incredibly slow on some systems (as much as two orders of magnitude slower than modifiyng the int[] array).

  2. there are no guarantee that a getRGB following a setRGB will give back the same pixel you passed

This last point is basically pretty clear from the JavaDoc of setRGB, which states:

...For images with an IndexColorModel, the index with the nearest color is chosen.

Seen I can work directly in a BufferedImage's int[] pixels, which I can access to by doing, for example:

 int[] a = ((DataBufferInt) tmp.getRaster().getDataBuffer()).getData();

I was wondering: are there any known drawbacks/gotchas when directly manipulating pixels in the int[]?

like image 620
SyntaxT3rr0r Avatar asked Dec 03 '10 18:12

SyntaxT3rr0r


1 Answers

The whole point of getData() giving you access to the backing int array is precisely for this optimization, so the benefits most likely outweigh the drawbacks.

The drawbacks depend on how you're using the buffered image. If you're drawing it to the screen while you're editing it, you may encounter some artifacts on the screen (like pixels not colored in time), in which case you should consider double buffering (which does involve copying over the entire image for every refresh).

like image 183
Ben Taitelbaum Avatar answered Nov 02 '22 19:11

Ben Taitelbaum