With BufferedImages, when creating a WritableRaster how do you ensure that it will be compatible with the specific ColorModel?

北城余情 提交于 2020-01-06 02:33:08

问题


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);
}

回答1:


The easiest way to make sure you have a WritableRaster that is compatible with your ColorModel is to first choose the color model, then create a raster from it like this:

ColorModel colorModel = ColorModel.getRGBdefault(); // Or any other color model
WritableRaster raster = colorModel.createCompatibleWritableRaster(width, height);

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 of java.awt.image.BufferedImage and the createCompatibleWritableRaster methods of the different ColorModel 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:

Raster.createPackedRaster(db,width,height,1,null);

...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:

int[] masks = new int[]{0xff0000, 0xff00, 0xff}; // Add 0xff000000 if you want alpha
Raster.createPackedRaster(db, width, height, width, masks, null); 

PS: You shouldn't need to to do the image.setRGB on the last line of your code, as the image is using your data array as its backing buffer already.



来源:https://stackoverflow.com/questions/18999430/with-bufferedimages-when-creating-a-writableraster-how-do-you-ensure-that-it-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!