首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从PPM文件加载的QImage显示不正确

从PPM文件加载的QImage显示不正确
EN

Stack Overflow用户
提问于 2020-09-16 08:41:14
回答 1查看 110关注 0票数 1

所以,我正在使用QT为我的类做一个图像操作任务,我被要求手动将当前的图像数据保存为PPM格式,并将其加载回QDialog程序。

我设法正确地保存了图像(用gimp验证了输出文件),但是从文件加载产生了如下所示的灾难

原文如下:

以及糟糕的加载:

下面是我的文件加载代码:

代码语言:javascript
运行
复制
//... 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...

当我从文件加载时,我希望显示看起来像原始图像,但我不确定导致损坏的错误原因,请帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-17 23:03:30

一行图像的大小是3 * width字节而不是width,因此这应该在data[]索引中的任何地方得到修复。

即代码

代码语言:javascript
运行
复制
data[width*h+w] = (unsigned char)readVal;

应替换为

代码语言:javascript
运行
复制
data[3*width*h+w] = (unsigned char)readVal;

和代码

代码语言:javascript
运行
复制
r = (int)data[width*h+w*3];
g = (int)data[width*h+w*3+1];
b = (int)data[width*h+w*3+2];

替换为

代码语言:javascript
运行
复制
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];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63911585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档