QImage :: setPixel:坐标超出范围

时间:2014-08-19 19:22:06

标签: c++ qt image-processing bmp

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

提前感谢:)

1 个答案:

答案 0 :(得分:0)

您错误地计算了此行的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] );