如何在 Qt 中使用 QImage 更改图像中的文本(前景)和背景颜色?
How change text (foreground) and background color in image using QImage in Qt?
我可以这样改变QImage的背景:
QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Darken);
painter.fillRect(image.rect(), QColor("#0000FF"));
我也可以这样改变QImage的前景:
QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Lighten);
painter.fillRect(image.rect(), QColor("#FF0000"));
但是如何同时更改它们?
注意:如果我们运行这两个代码,结果将是错误的。
我找到了答案。
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]));
}
}
}
和:
QColor foreground = QColor("#FF0000");
QColor background = QColor("#0000FF");
recolor(&image, foreground, background);
我从“Okular”程序的源代码中得到这段代码。
我可以这样改变QImage的背景:
QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Darken);
painter.fillRect(image.rect(), QColor("#0000FF"));
我也可以这样改变QImage的前景:
QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Lighten);
painter.fillRect(image.rect(), QColor("#FF0000"));
但是如何同时更改它们?
注意:如果我们运行这两个代码,结果将是错误的。
我找到了答案。
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]));
}
}
}
和:
QColor foreground = QColor("#FF0000");
QColor background = QColor("#0000FF");
recolor(&image, foreground, background);
我从“Okular”程序的源代码中得到这段代码。