PDA

View Full Version : QImage doesn't seem to load any images at all (always returning null)?



SaldaVonSchwartz
11th April 2012, 11:17
I'm on Windows7 and using Qt SDK 4.8.
Trying to read a file in with QImage but it just doesn't seem to load. That is, QImage(filename) or QImage(filename, "PNG") or QImage.load(filename) always return NULL.

Here's my code:


QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Image"),
QDir::homePath(),
tr("Image Files (*.png *.tga *.bmp)"));

if (!fileName.isEmpty())
{
targetImage = new QImage(fileName, "PNG");
if(targetImage->isNull())
{
QMessageBox::information(this,
tr("Viewer"),
tr("Cannot load %1.").arg(fileName));
return;
}

onScreenImage.setBackgroundRole(QPalette::Base);
onScreenImage.setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
onScreenImage.setScaledContents(true);
onScreenImage.setPixmap(QPixmap::fromImage(*target Image));
}
}

What am I doing wrong?

Berryblue031
11th April 2012, 12:28
targetImage = new QImage(fileName, "PNG");

Remove the optional format parameter ("PNG") and just use the default so QImage will autodetect the file type otherwise you need to filter QFileDialog only to png files


QString fileName = QFileDialog::getOpenFileName(...

What is the value of fileName here? For QImage you will need the full path not just the fileName.

Ricardo_arg
25th April 2012, 01:40
onScreenImage.setPixmap(QPixmap::fromImage(*target Image));
i think you have to cahnge this. hope it helps
onScreenImage.setPixmap(QPixmap::fromImage(targetI mage));

ChrisW67
25th April 2012, 02:22
Comments embedded:



QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Image"),
QDir::homePath(),
tr("Image Files (*.png *.tga *.bmp)"));
// you could have a BMP or Targa file at this point
// Qt has no Targa format support out of the box
if (!fileName.isEmpty())
{
targetImage = new QImage(fileName, "PNG");
// Not much good if the file is not a PNG
// You allocate memory you do not free: memory leak
// No need for this to be on the heap at all

if(targetImage->isNull())
{
QMessageBox::information(this,
tr("Viewer"),
tr("Cannot load %1.").arg(fileName));
return;
}

onScreenImage.setBackgroundRole(QPalette::Base);
onScreenImage.setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
onScreenImage.setScaledContents(true);
onScreenImage.setPixmap(QPixmap::fromImage(*target Image));
// Why did you use a QImage if you require a QPixmap ultimately?
}
}


You don't say if it is failing in the development or deployed environment. None of this will work deployed unless you also deploy the necessary imageformat plugins. What does QImageReader::supportedImageFormats() return?