Take the 2-minute tour ×

I am trying to implement a painting tool with layer support. For each layer I create a WritableRaster. To display the canvas, the layers have to be merged. What's the most efficient way to do this? I could use a bufferedImage, set the raster and draw each layer to the Graphics context with a alpha composite. But isn't it better/faster to merge it on data level and then draw a single image?

Edit: I did some profiling. This is what my current approach looks like:

//tmp.getRaster().setRect(layer.getRaster()); // VERY slow
tmp.getRaster().setDataElements(0, 0, layer.getRaster()); //slow
g2.drawImage(tmp, 0, 0, scaledDim.width, scaledDim.height, null);

I used BufferedImages instead of WritableRasters for each layer before and there was no delay noticeable.

My next step would be to cache top and bottom layers, so there would be only 3 images to be drawn. That would probably solve the problem.

share|improve this question

4 Answers 4

My sense is that drawing a raster is roughly equivalent to "merging it on a data level".

I wouldn't worry about this unless you notice it's a bottleneck.

share|improve this answer

maybe you can use JAI:

ParameterBlock pb = new ParameterBlock();
RenderedImage ri = JAI.create("xor",pb);
share|improve this answer

If you blit (draw) them each onto an image buffer, you are probably using graphics-card acceleration.

If you loop through the indivual buffers and merge them by hand (I assume this is what you mean by "Do it on the data level"), you will be using the CPU.

So actually, doing it by hand will be significantly slower than blitting.

So, your original solution is best. Let the graphics card do its job, it's very good at it.

share|improve this answer

Ok, so I introduced a upper and a lower layer cache and now I got a pretty good performance. I can add as many layers as my memory can handle without affecting rendering time.

share|improve this answer

Your Answer


