gpt4 book ai didi

qt - 如何在 Qt 中使用 QImage 更改图像中的文本(前景)和背景颜色?

转载 作者:行者123 更新时间:2023-11-30 04:58:20 29 4
gpt4 key购买 nike

我可以通过这样做来改变 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”程序的源代码中得到这段代码。

关于qt - 如何在 Qt 中使用 QImage 更改图像中的文本(前景)和背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51685694/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com