【问题标题】:QImage::setPixel: coordinate out of rangeQImage::setPixel: 坐标超出范围
【发布时间】:2024-05-18 09:15:01
【问题描述】:

我是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]));
        }
    }

提前感谢:)

【问题讨论】:

    标签: c++ qt image-processing bmp


    【解决方案1】:

    你错误地计算了这条线上的 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
    

    应该是

     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] );
    

    【讨论】:

    • 仍然超出范围 :(