如何将具有ComponentColorModel的BufferedImage转换为SWT ImageData?

This SWT snippet将BufferedImage转换为SWT ImageData:

static ImageData convertToSWT(BufferedImage bufferedImage) {
    if (bufferedImage.getColorModel() instanceof DirectColorModel) {
        ...
    } else if (bufferedImage.getColorModel() instanceof IndexColorModel) {
        ...
    }
    return null;
}

问题是,ColorModel有第三个子类:ComponentColorModel.我需要使用这种颜色模型转换图像.我该怎么做?

解决方法:

发现here(但请注意crosay答案中的补丁!)

if (bufferedImage.getColorModel() instanceof ComponentColorModel) {
    ComponentColorModel colorModel = (ComponentColorModel)bufferedImage.getColorModel();

    //ASSUMES: 3 BYTE BGR IMAGE TYPE

    PaletteData palette = new PaletteData(0x0000FF, 0x00FF00,0xFF0000);
    ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette);

    //This is valid because we are using a 3-byte Data model with no transparent pixels
    data.transparentPixel = -1;

    WritableRaster raster = bufferedImage.getRaster();
    int[] pixelArray = new int[3];
    for (int y = 0; y < data.height; y++) {
        for (int x = 0; x < data.width; x++) {
            raster.getPixel(x, y, pixelArray);
            int pixel = palette.getPixel(new RGB(pixelArray[0], pixelArray[1], pixelArray[2]));
            data.setPixel(x, y, pixel);
        }
    }
    return data;
上一篇:java – 在另一个缓冲的图像上绘制缓冲图像


下一篇:从ByteArrayInputStream创建BufferedImage的Java错误