Search code examples
c++qtqimagecolor-space

QImage Custom Indexed Colors Using setColorTable


In my project I need to convert an image with many colors to one that only uses any of the 144 predetermined colors I set in a custom colorTable.

Here is my code:

    QImage convImage(128, 128, QImage::Format_Indexed8);
    convImage.setColorCount(144);
    convImage.setColorTable(colorTable); //colorTable is a const QVector with 144 qRgb values.

    //scaledImage is the source image
    convImage = scaledImage.convertToFormat(QImage::Format_Indexed8,Qt::ThresholdDither|Qt::AutoColor);

    ui->mapView->setPixmap(QPixmap::fromImage(convImage));

I would expect convImage to only contain colors that exist in the colorTable I created, however it seems to completely ignore the table I set and instead creates it's own unique table with 256 max colors.

I could index everything myself by looping through every pixel and find a way to accurately select a color from the colorTable, but I am wondering if I am just using the colorTable wrong. I couldn't find anything in the documentation that explains why a new table is being created.

Thanks for your time.


Solution

  • Well, ask yourself: how should the convertToFormat() call on scaledImage possibly know about the colortable you applied to convImage? It doesn't know anything about the convImage on the left-hand-side.

    Fortunately, there's an overload of convertToFormat that takes a colortable and should do the job:

    QImage convImage = scaledImage.convertToFormat (QImage::Format_Indexed8, 
                                                    colorTable,                                
                                                    Qt::ThresholdDither|Qt::AutoColor);