4

This SWT snippet converts a BufferedImage to SWT ImageData:

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

The problem is, there is a third subclass of ColorModel: ComponentColorModel. And I need to convert an image using this color model. How do I do it?

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487

2 Answers2

6

Found here (but mind the patch in crosay's answer!)

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;
Campa
  • 4,267
  • 3
  • 37
  • 42
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
5

In Romanov's answer, change the following line:

int[] pixelArray = new int[3];

with

int[] pixelArray = colorModel.getComponentSize();
Campa
  • 4,267
  • 3
  • 37
  • 42
crosay
  • 51
  • 1
  • 1