QImageWriter: Detect failure due to trying to write a QImage()

This is not a bug in QImageWriter, but caller code. We should be
explicit about what the problem was so it can be fixed.

[ChangeLog][QtGui][QImageWriter] Add QImageWriter::InvalidImageError to
communicate invalid attempts to write a bad QImage (for instance, a null
QImage).

Change-Id: I0333b8263f1da1c672bed17dab48bfd6cafe41a2
Reviewed-by: Eirik Aavitsland <eirik.aavitsland@qt.io>
bb10
Robin Burchell 2017-02-10 15:37:12 +01:00
parent 1631384c27
commit 7a717aaf45
3 changed files with 28 additions and 1 deletions

View File

@ -87,6 +87,9 @@
\value UnsupportedFormatError Qt does not support the requested
image format.
\value InvalidImageError An attempt was made to write an invalid QImage. An
example of an invalid image would be a null QImage.
\value UnknownError An unknown error occurred. If you get this
value after calling write(), it is most likely caused by a bug in
QImageWriter.
@ -736,6 +739,13 @@ extern void qt_imageTransform(QImage &src, QImageIOHandler::Transformations orie
*/
bool QImageWriter::write(const QImage &image)
{
// Do this before canWrite, so it doesn't create a file if this fails.
if (Q_UNLIKELY(image.isNull())) {
d->imageWriterError = QImageWriter::InvalidImageError;
d->errorString = QImageWriter::tr("Image is empty");
return false;
}
if (!canWrite())
return false;

View File

@ -60,7 +60,8 @@ public:
enum ImageWriterError {
UnknownError,
DeviceError,
UnsupportedFormatError
UnsupportedFormatError,
InvalidImageError
};
QImageWriter();

View File

@ -77,6 +77,9 @@ private slots:
void saveWithNoFormat();
void saveToTemporaryFile();
void writeEmpty();
private:
QTemporaryDir m_temporaryDir;
QString prefix;
@ -529,5 +532,18 @@ void tst_QImageWriter::saveToTemporaryFile()
}
}
void tst_QImageWriter::writeEmpty()
{
// check writing a null QImage errors gracefully
QTemporaryDir dir;
QVERIFY2(dir.isValid(), qPrintable(dir.errorString()));
QString fileName(dir.path() + QLatin1String("/testimage.bmp"));
QVERIFY(!QFileInfo(fileName).exists());
QImageWriter writer(fileName);
QVERIFY(!writer.write(QImage()));
QCOMPARE(writer.error(), QImageWriter::InvalidImageError);
QVERIFY(!QFileInfo(fileName).exists());
}
QTEST_MAIN(tst_QImageWriter)
#include "tst_qimagewriter.moc"