I have to fill a BufferedImage with the content of a custom Image, because I want to display my custom image in a JFrame.
I used a simple for-Loop before I checked my code with a Profiler:
for(int x = 0; x < width, x++)
for(int y = 0; y < height; y++)
bufferedImage.setRGB(x, height-y-1, toIntColor( customImage.get(x,y) ));
That worked but I decided to try it concurrent. This Code divides the Image into columns, and should copy each column parallel (code snippet simplified):
final ExecutorService pool = Executors.newCachedThreadPool();
final int columns = Runtime.getRuntime().availableProcessors() +1;
final int columnWidth = getWidth() / columns;
for(int column = 0; column < columns; column++){
final Rectangle tile = Rectangle.bottomLeftRightTop(
0,
columnWidth*column,
columnWidth*(column+1),
height
);
pool.execute(new ImageConverter(tile));
}
pool.shutdown();
pool.awaitTermination( timeoutSeconds, TimeUnit.SECONDS);
ImageConverterRunnable:
private final class ImageConverter implements Runnable {
private final Rectangle tile;
protected ImageConverter(Rectangle tile){ this.tile = tile; }
@Override public void run(){
for(int x = tile.left; x < tile.right; x++)
for(int y = tile.bottom; y < tile.top; y++)
bufferedImage.setRGB(x, height-y-1, toIntColor( customImage.get(x,y) )); }
}
I noticed that the concurrent solution took about two to three times longer than the simple for-Loop. I already looked for questions like this and googled, but I didn't find anything.
Why does it take so Long? It it because the awaitTermination() line? Is there maybe a better solution for converting Images?
Thanks in advance, Johannes :)
EDIT:
I have performed some testing. All conversions measured were preceeded by a warmup of 3000 Image conversions.
the simple for-Loop takes 7 to 8 milliseconds to copy the Bitmap.
The parallel Image copying took 20 to 24 milliseconds per image. without warm-up it took 60 milliseconds.