QRgb QImage::pixel(const QPoint &position) const
Returns the color of the pixel at the given position.
If the position is not valid, the results are undefined.
Warning: This function is expensive when used for massive pixel manipulations. Use constBits() or constScanLine() when many pixels needs to be read.
See also setPixel(), valid(), constBits(), constScanLine(), and Pixel Manipulation.
⚠️ 警告:性能问题
"Warning: This function is expensive when used for massive pixel manipulations."
⚠️ (警告: 该函数在大规模像素操作时代价昂贵)
为什么
pixel(x, y)
慢?
QImage::pixel()
需要内部做格式转换,以适配不同的QImage
存储格式(如Format_RGB32
,Format_Indexed8
)。- 它是逐像素操作,每次调用都会执行额外的安全检查,因此在循环中大量使用时会变慢。
如何优化?
如果你需要访问大量像素(如遍历整个图片),推荐使用
constBits()
或constScanLine()
直接访问原始数据:
const uchar *data = image.constBits();
int bytesPerLine = image.bytesPerLine();for (int y = 0; y < image.height(); ++y) {const QRgb *line = reinterpret_cast<const QRgb *>(data + y * bytesPerLine);for (int x = 0; x < image.width(); ++x) {QRgb pixelColor = line[x]; // 直接访问像素int r = qRed(pixelColor);int g = qGreen(pixelColor);int b = qBlue(pixelColor);}
}
这样访问像素比 pixel(x, y)
快很多,因为它直接操作数据缓冲区,避免了函数调用开销。