Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BufferedImage which has a ComponentColorModel to SWT ImageData?

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?

like image 995
Alexey Romanov Avatar asked Dec 22 '22 05:12

Alexey Romanov


2 Answers

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;
like image 166
Alexey Romanov Avatar answered Dec 24 '22 02:12

Alexey Romanov


In Romanov's answer, change the following line:

int[] pixelArray = new int[3];

with

int[] pixelArray = colorModel.getComponentSize();
like image 35
crosay Avatar answered Dec 24 '22 01:12

crosay