c++ - 从PPM文件加载的QImage无法正确显示

标签 c++ qt render loading qimage

因此,我正在使用QT为我的类(class)进行图像操作分配,要求我将当前拥有的图像数据手动保存为PPM格式,然后将其重新加载到QDialog程序中。
我设法正确保存了图像(使用gimp验证了输出文件),但是从文件中加载造成了如下所示的灾难
这是原始文件:

以及不良的负载:

这是我的文件加载代码:

//... opens the file and pulling out headers & etc...

            unsigned char* data = new unsigned char[width*height*3];

            //Manual loading each byte into char array
            for(long h = 0; h < height; h++){ //for all 600 rows
                getline(readPPM,temp); //readPPM is an ifstream, temp is a string
                std::stringstream oneLine(temp);

                for(long w = 0; w < width*3; w++){ //to every position in that line 800*3
                    int readVal;
                    oneLine >> readVal; //string stream autofill get the int value instead of just one number
                    data[width*h+w] = (unsigned char)readVal; //put it into unsign char
                }
            }


            //Method 1: create the QImage with constructor 
(it blacked out 2/3 of the bottom of the image, and I'm not exactly familiar with QImage data type)
            imageData = QImage(data,width,height,QImage::Format_BGR888);

            //Method 2: manually setting each pixel
            for(int h = 0; h < height; h++){
                for(int w = 0; w < width; w++){
                    int r,g,b;
                    r = (int)data[width*h+w*3];
                    g = (int)data[width*h+w*3+1];
                    b = (int)data[width*h+w*3+2];
                    QColor color = qRgb(r,g,b);
                    imageData.setPixelColor(w,h,color);
                }
            }

//...set image to display...

从文件加载时,我希望显示的图像看起来像原始图像,并且不确定导致损坏的问题是什么,请帮助

最佳答案

一行图像的大小为3 * width字节,而不是width,因此应在data[]索引中的所有位置固定该大小。
即码

data[width*h+w] = (unsigned char)readVal;
应该替换为
data[3*width*h+w] = (unsigned char)readVal;
和代码
r = (int)data[width*h+w*3];
g = (int)data[width*h+w*3+1];
b = (int)data[width*h+w*3+2];
替换为
r = (int)data[3*width*h+w*3];
g = (int)data[3*width*h+w*3+1];
b = (int)data[3*width*h+w*3+2];

关于c++ - 从PPM文件加载的QImage无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63911585/

相关文章:

c++ - 如何在 Qt 中打印 QWidget?

javascript - 根据状态和索引动态更改样式组件

php - 如何将 TWIG 输出渲染到变量以供以后使用(symfony2)?

c++ - 尝试逐个像素地理解位图

c++ - 没有对象不能调用成员函数,但我用对象调用函数

c++ - QByteArray 值比较

android - 图像无法在 Android 7.0 (API 24) 上呈现

c++ - 在 Qt 中将 T 的集合转换为 QVariant 的集合

c++ - 如何使用黑名单/通过唯一标识 dll 来阻止 dll 注入(inject)?

c++ - 无法打开sqlite数据库