alihardan
alihardan

Reputation: 350

How change text (foreground) and background color in image using QImage in Qt?

I can change the background of QImage by doing this:

QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Darken);
painter.fillRect(image.rect(), QColor("#0000FF"));

I can also change the foreground of QImage by doing this:

QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Lighten);
painter.fillRect(image.rect(), QColor("#FF0000"));

But how change both of them at once?

Note: If we run both of this codes, the result will be wrong.

Upvotes: 1

Views: 1250

Answers (1)

alihardan
alihardan

Reputation: 350

I found the answer.

void ClassName:recolor(QImage *image, const QColor &foreground, const QColor &background)
{
    if (image->format() != QImage::Format_ARGB32_Premultiplied) {
        // qCWarning(OkularUiDebug) << "Wrong image format! Converting...";
        *image = image->convertToFormat(QImage::Format_ARGB32_Premultiplied);
    }

    Q_ASSERT(image->format() == QImage::Format_ARGB32_Premultiplied);

    const float scaleRed = background.redF() - foreground.redF();
    const float scaleGreen = background.greenF() - foreground.greenF();
    const float scaleBlue = background.blueF() - foreground.blueF();

    for (int y=0; y<image->height(); y++) {
        QRgb *pixels = reinterpret_cast<QRgb*>(image->scanLine(y));

        for (int x=0; x<image->width(); x++) {
            const int lightness = qGray(pixels[x]);
            pixels[x] = qRgba(scaleRed * lightness + foreground.red(),
                           scaleGreen * lightness + foreground.green(),
                           scaleBlue * lightness + foreground.blue(),
                           qAlpha(pixels[x]));
        }
    }
}

and:

QColor foreground = QColor("#FF0000");
QColor background = QColor("#0000FF");
recolor(&image, foreground, background);

I got this code from the source code of "Okular" program.

Upvotes: 3

Related Questions