QImage::setPixel:坐标超出范围

QImage::setPixel: coordinate out of range

本文关键字:范围 坐标 setPixel QImage      更新时间:2023-10-16

我是QT初学者

我试着打开二进制文件并逐像素绘制

当我调试

时,我得到了这个警告
QImage::setPixel: coordinate (67,303) out of range
QImage::setPixel: coordinate (67,306) out of range
QImage::setPixel: coordinate (67,309) out of range
QImage::setPixel: coordinate (67,312) out of range

这是代码

    unsigned char* data = new unsigned char[row_padded];
    unsigned char tmp;
    QImage myImage;
    myImage = QImage(width, height, QImage::Format_RGB888);
    for(int i = 0; i < height; i++)
    {
        fread(data, sizeof(unsigned char), row_padded, file);
        for(int j = 0; j < width*3; j += 3)
        {
            // Convert (B, G, R) to (R, G, B)
            tmp = data[j];
            data[j] = data[j+2];
            data[j+2] = tmp;
                    myImage.setPixel((width*3)-j, height-i, RGB((int)data[j],(int)data[j+1],(int)data[j+2]));
        }
    }

提前感谢:)

您错误地计算了这一行的x和y坐标:

myImage.setPixel((width*3)-j, height-i, RGB((int)data[j],(int)data[j+1],(int)data[j+2]));

x应该改为:

 width - j / 3 - 1

y应该是

 height - i - 1

或者最好为x使用另一个变量来避免除法:

for(int i = 0; i < height; i++)
{
    fread(data, sizeof(unsigned char), row_padded, file);
    int x = width;
    for(int j = 0; j < width*3; j += 3)
    {
        // Convert (B, G, R) to (R, G, B)
        tmp = data[j];
        data[j] = data[j+2];
        data[j+2] = tmp;
        myImage.setPixel(--x, height-i-1, RGB((int)data[j],(int)data[j+1],(int)data[j+2]));
    }
}

建议:最好在使用变量之前定义它:

unsigned char tmp = data[j];
data[j] = data[j+2];
data[j+2] = tmp;

或者更好的

std::swap( data[j], data[j+2] );