I'm programming in C++ on Qt Creator, with a CImagePPM class allowing to manipulate images in PPM format (opening, rotations, etc).
I have a problem when opening an image file (the strat.ppm file located in the project directory), with the opening error message ("Impossible to open the file!").
The opening is handled by the CImagePPM constructor.
Here is the code of CImagePPM.h :
#ifndef CIMAGEPPM_H
#define CIMAGEPPM_H
#include <iostream>
#include <fstream>
#include <QPainter>
#include <string>
using namespace std;
struct rgb
{
int r,g,b;
};
class CImagePPM
{
public:
CImagePPM();
CImagePPM(string nomfich);
~CImagePPM();
void dessiner(QPainter * p);
void rot90Droite();
private:
int largeur;
int hauteur;
int intensiteMax;
rgb** pixels;
};
#endif
And that of CImagePPM.cpp :
#include "cimageppm.h"
#include <fstream>
CImagePPM::CImagePPM()
{
largeur=200;
hauteur=100;
intensiteMax=255;
pixels=new rgb*[hauteur];
for (int i=0;i<hauteur;i++) {
pixels[i]=new rgb[largeur];
pixels[i]->r=0;
pixels[i]->g=0;
pixels[i]->b=0;
}
}
CImagePPM::CImagePPM(string nomfich) {
ifstream fichier(nomfich.c_str(), ios::in);
string temp;
if (!fichier.fail()) {
fichier >> temp;
fichier >> this->largeur;
fichier >> this->hauteur;
fichier >> this->intensiteMax;
pixels=new rgb*[this->hauteur];
for (int i=0;i<hauteur;i++) {
pixels=new rgb*[this->largeur];
for (int j=0;j<largeur;j++) {
fichier >> this->pixels[i][j].r >> this->pixels[i][j].g >> this->pixels[i][j].b;
}
fichier.close();
}
}
else cerr << "Impossible d'ouvrir le fichier!" << endl;
}
CImagePPM::~CImagePPM() {
for (int i=0;i<hauteur;i++) {
delete pixels[i];
}
}
void CImagePPM::dessiner(QPainter * p) {
for (int i=0;i<hauteur;i++) {
for (int j=0;j<largeur;j++) {
p->setPen(QColor(pixels[i][j].r,pixels[i][j].g,pixels[i][j].b));
p->drawPoint(j,i);
}
}
}
And finally mainwindow.cpp :
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "cimageppm.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
img=new CImagePPM();
CImagePPM img("strat.ppm");
}
MainWindow::~MainWindow()
{
delete ui;
delete img;
}
void MainWindow::paintEvent(QPaintEvent* e) {
QWidget::paintEvent(e);
QPainter painter(this);
if (img!=NULL) {
img->dessiner(&painter);
}
}
Update : When I put the file in the build directory, it crashes.
Update 2 : I corrected the lines as below and it no longer crashes. The file is loaded properly but the image is a black rectangle with the correct size.
pixels=new rgb*[this->hauteur];
for (int i=0;i<hauteur;i++) {
pixels[i]=new rgb[this->largeur];
for (int j=0;j<largeur;j++) {
fichier >> pixels[i][j].r >> pixels[i][j].g >> pixels[i][j].b;
}
Update 3 : I moved the file to the build directory and corrected a mistake in the constructor (the file was closed too soon) and the image shows.