I'm learning to use BufferedImages in java, and am trying to create an animation where each frame of the animation is the result of mathematically fiddling around with pixel data. I'm just playing around really. Originally I was using an indexed ColorModel, but I've changed it (to take advantage of more colors) to a direct ColorModel. But now an error crops up saying -
Raster sun.awt.image.SunWritableRaster@29c204 is incompatible with ColorModel DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=ff000000
The code I was using to create the BufferedImage and WriteableRaster is here:
public void initialize(){
int width = getSize().width;
int height = getSize().height;
data = new int [width * height];
DataBuffer db = new DataBufferInt(data,height * width);
WritableRaster wr = Raster.createPackedRaster(db,width,height,1,null);
image = new BufferedImage(ColorModel.getRGBdefault(),wr,false,null);
image.setRGB(0, 0, width, height, data, 0, width);
}
The easiest way to make sure you have a
WritableRaster
that is compatible with yourColorModel
is to first choose the color model, then create a raster from it like this:However, this might not be practical, for example in situations like yours where you create a
DataBuffer
from an existing array. In that case, I would actually recommend looking at the source code of the constructors ofjava.awt.image.BufferedImage
and thecreateCompatibleWritableRaster
methods of the differentColorModel
implementations (that's the way I taught myself how to do it :-). It shows the most common combinations of rasters and color models that work well together.Your line:
...seem to be creating a raster with
MultiPixelPackedSampleModel
and 1 bit per pixel... Both of these are probably incompatible with the RGB color model. What you want is probably want is:PS: You shouldn't need to to do the
image.setRGB
on the last line of your code, as the image is using yourdata
array as its backing buffer already.