2D Rendering Advice

I am writing an application that decodes image data from a network stream and then renders it. I need two rendering modes, one for on screen rendering and one for image rendering to disk. Because the data is often raw pixels, I am currently using the code below to allow access to the pixel data directly and then copy the changed pixels to the regular BufferedImage. When the data stream has a line or rectangle encoded, I draw directly to the BufferedImage. Is there a faster/smarter way to do this? I have tried accessing the pixels stored in the DataBufferInt rather than using the pixel[] below and performance is horrendous.

Thanks in advance for any suggestions.

pixels = new int[width * height];
memImageSrc = new MemoryImageSource(width, height, colorModel, pixels, 0, width);
memImageSrc.setAnimated(true);

memImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
memGraphics = memImage.getGraphics();
pixelsSource = new MemoryImageSource(width, height, colorModel, pixels, 0, width);
pixelsSource.setAnimated(true);
rawPixelsImage = Toolkit.getDefaultToolkit().createImage(pixelsSource);

Not sure if this will help, but here’s code for accessing pixel[] arrays in a BufferedImage quickly, so you don’t have to copy from a MemoryImageSource.


        int w = getWidth();
        int h = getHeight();
        int[] pixels = new int[w * h];
        
        DirectColorModel colorModel = 
            new DirectColorModel(24, 0xff0000, 0x00ff00, 0x0000ff);

        SampleModel sampleModel = new SinglePixelPackedSampleModel(
            DataBuffer.TYPE_INT, w, h, new int[] { 0xff0000, 0x00ff00, 0x0000ff }); 
        
        DataBuffer dataBuffer = new DataBufferInt(pixels, w * h);
        
        WritableRaster raster = Raster.createWritableRaster(
            sampleModel, dataBuffer, new Point(0,0));
        
        awtImage = new BufferedImage(colorModel, raster, true, new Hashtable());

And does that end up being quicker than using the WritableRaster that is supplied by the BufferedImage automatically? I tried


int[] pixels = ((DataBufferInt)memImage.getRaster().getDataBuffer()).getData(0);

and it ends up being much slower than the version I have now

My two cents:

I recommend never ever touching the DataBuffer of an image. I explain why here:

I’ve had good performance with:
bi.getRaster().setDataElements(x,y,w,h,data)

But “good” is a vague word depending on the size of the animation, the minimum system specs of your app, etc.

It ends up being much faster than what is supplied by BufferedImage automatically. You actually write directly to the pixels[] buffer