/src/gui/image/qimagewriter.cpp

https://bitbucket.org/ultra_iter/qt-vtl · C++ · 734 lines · 346 code · 57 blank · 331 comment · 89 complexity · 9612d5d4d71754b9e84f08bed9dbf87b MD5 · raw file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
  4. ** All rights reserved.
  5. ** Contact: Nokia Corporation (qt-info@nokia.com)
  6. **
  7. ** This file is part of the QtGui module of the Qt Toolkit.
  8. **
  9. ** $QT_BEGIN_LICENSE:LGPL$
  10. ** GNU Lesser General Public License Usage
  11. ** This file may be used under the terms of the GNU Lesser General Public
  12. ** License version 2.1 as published by the Free Software Foundation and
  13. ** appearing in the file LICENSE.LGPL included in the packaging of this
  14. ** file. Please review the following information to ensure the GNU Lesser
  15. ** General Public License version 2.1 requirements will be met:
  16. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  17. **
  18. ** In addition, as a special exception, Nokia gives you certain additional
  19. ** rights. These rights are described in the Nokia Qt LGPL Exception
  20. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  21. **
  22. ** GNU General Public License Usage
  23. ** Alternatively, this file may be used under the terms of the GNU General
  24. ** Public License version 3.0 as published by the Free Software Foundation
  25. ** and appearing in the file LICENSE.GPL included in the packaging of this
  26. ** file. Please review the following information to ensure the GNU General
  27. ** Public License version 3.0 requirements will be met:
  28. ** http://www.gnu.org/copyleft/gpl.html.
  29. **
  30. ** Other Usage
  31. ** Alternatively, this file may be used in accordance with the terms and
  32. ** conditions contained in a signed written agreement between you and Nokia.
  33. **
  34. **
  35. **
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. /*!
  42. \class QImageWriter
  43. \brief The QImageWriter class provides a format independent interface
  44. for writing images to files or other devices.
  45. \reentrant
  46. \ingroup painting
  47. \ingroup io
  48. QImageWriter supports setting format specific options, such as the
  49. gamma level, compression level and quality, prior to storing the
  50. image. If you do not need such options, you can use QImage::save()
  51. or QPixmap::save() instead.
  52. To store an image, you start by constructing a QImageWriter
  53. object. Pass either a file name or a device pointer, and the
  54. image format to QImageWriter's constructor. You can then set
  55. several options, such as the gamma level (by calling setGamma())
  56. and quality (by calling setQuality()). canWrite() returns true if
  57. QImageWriter can write the image (i.e., the image format is
  58. supported and the device is open for writing). Call write() to
  59. write the image to the device.
  60. If any error occurs when writing the image, write() will return
  61. false. You can then call error() to find the type of error that
  62. occurred, or errorString() to get a human readable description of
  63. what went wrong.
  64. Call supportedImageFormats() for a list of formats that
  65. QImageWriter can write. QImageWriter supports all built-in image
  66. formats, in addition to any image format plugins that support
  67. writing.
  68. \sa QImageReader, QImageIOHandler, QImageIOPlugin
  69. */
  70. /*!
  71. \enum QImageWriter::ImageWriterError
  72. This enum describes errors that can occur when writing images with
  73. QImageWriter.
  74. \value DeviceError QImageWriter encountered a device error when
  75. writing the image data. Consult your device for more details on
  76. what went wrong.
  77. \value UnsupportedFormatError Qt does not support the requested
  78. image format.
  79. \value UnknownError An unknown error occurred. If you get this
  80. value after calling write(), it is most likely caused by a bug in
  81. QImageWriter.
  82. */
  83. #include "qimagewriter.h"
  84. #include <qbytearray.h>
  85. #include <qfile.h>
  86. #include <qfileinfo.h>
  87. #include <qimageiohandler.h>
  88. #include <qset.h>
  89. #include <qvariant.h>
  90. // factory loader
  91. #include <qcoreapplication.h>
  92. #include <private/qfactoryloader_p.h>
  93. // image handlers
  94. #include <private/qbmphandler_p.h>
  95. #include <private/qppmhandler_p.h>
  96. #include <private/qxbmhandler_p.h>
  97. #include <private/qxpmhandler_p.h>
  98. #ifndef QT_NO_IMAGEFORMAT_PNG
  99. #include <private/qpnghandler_p.h>
  100. #endif
  101. #ifndef QT_NO_IMAGEFORMAT_JPEG
  102. #include <private/qjpeghandler_p.h>
  103. #endif
  104. #ifndef QT_NO_IMAGEFORMAT_MNG
  105. #include <private/qmnghandler_p.h>
  106. #endif
  107. #ifndef QT_NO_IMAGEFORMAT_TIFF
  108. #include <private/qtiffhandler_p.h>
  109. #endif
  110. #ifdef QT_BUILTIN_GIF_READER
  111. #include <private/qgifhandler_p.h>
  112. #endif
  113. QT_BEGIN_NAMESPACE
  114. #ifndef QT_NO_LIBRARY
  115. Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
  116. (QImageIOHandlerFactoryInterface_iid, QLatin1String("/imageformats")))
  117. #endif
  118. static QImageIOHandler *createWriteHandlerHelper(QIODevice *device,
  119. const QByteArray &format)
  120. {
  121. QByteArray form = format.toLower();
  122. QByteArray suffix;
  123. QImageIOHandler *handler = 0;
  124. #ifndef QT_NO_LIBRARY
  125. // check if any plugins can write the image
  126. QFactoryLoader *l = loader();
  127. QStringList keys = l->keys();
  128. int suffixPluginIndex = -1;
  129. #endif
  130. if (device && format.isEmpty()) {
  131. // if there's no format, see if \a device is a file, and if so, find
  132. // the file suffix and find support for that format among our plugins.
  133. // this allows plugins to override our built-in handlers.
  134. if (QFile *file = qobject_cast<QFile *>(device)) {
  135. if (!(suffix = QFileInfo(file->fileName()).suffix().toLower().toLatin1()).isEmpty()) {
  136. #ifndef QT_NO_LIBRARY
  137. int index = keys.indexOf(QString::fromLatin1(suffix));
  138. if (index != -1)
  139. suffixPluginIndex = index;
  140. #endif
  141. }
  142. }
  143. }
  144. QByteArray testFormat = !form.isEmpty() ? form : suffix;
  145. #ifndef QT_NO_LIBRARY
  146. if (suffixPluginIndex != -1) {
  147. // when format is missing, check if we can find a plugin for the
  148. // suffix.
  149. QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(QString::fromLatin1(suffix)));
  150. if (plugin && (plugin->capabilities(device, suffix) & QImageIOPlugin::CanWrite))
  151. handler = plugin->create(device, suffix);
  152. }
  153. #endif // QT_NO_LIBRARY
  154. // check if any built-in handlers can write the image
  155. if (!handler && !testFormat.isEmpty()) {
  156. if (false) {
  157. #ifndef QT_NO_IMAGEFORMAT_PNG
  158. } else if (testFormat == "png") {
  159. handler = new QPngHandler;
  160. #endif
  161. #ifndef QT_NO_IMAGEFORMAT_JPEG
  162. } else if (testFormat == "jpg" || testFormat == "jpeg") {
  163. handler = new QJpegHandler;
  164. #endif
  165. #ifndef QT_NO_IMAGEFORMAT_MNG
  166. } else if (testFormat == "mng") {
  167. handler = new QMngHandler;
  168. #endif
  169. #ifndef QT_NO_IMAGEFORMAT_TIFF
  170. } else if (testFormat == "tif" || testFormat == "tiff") {
  171. handler = new QTiffHandler;
  172. #endif
  173. #ifdef QT_BUILTIN_GIF_READER
  174. } else if (testFormat == "gif") {
  175. handler = new QGifHandler;
  176. #endif
  177. #ifndef QT_NO_IMAGEFORMAT_BMP
  178. } else if (testFormat == "bmp") {
  179. handler = new QBmpHandler;
  180. #endif
  181. #ifndef QT_NO_IMAGEFORMAT_XPM
  182. } else if (testFormat == "xpm") {
  183. handler = new QXpmHandler;
  184. #endif
  185. #ifndef QT_NO_IMAGEFORMAT_XBM
  186. } else if (testFormat == "xbm") {
  187. handler = new QXbmHandler;
  188. handler->setOption(QImageIOHandler::SubType, testFormat);
  189. #endif
  190. #ifndef QT_NO_IMAGEFORMAT_PPM
  191. } else if (testFormat == "pbm" || testFormat == "pbmraw" || testFormat == "pgm"
  192. || testFormat == "pgmraw" || testFormat == "ppm" || testFormat == "ppmraw") {
  193. handler = new QPpmHandler;
  194. handler->setOption(QImageIOHandler::SubType, testFormat);
  195. #endif
  196. }
  197. }
  198. #ifndef QT_NO_LIBRARY
  199. if (!testFormat.isEmpty()) {
  200. for (int i = 0; i < keys.size(); ++i) {
  201. QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(keys.at(i)));
  202. if (plugin && (plugin->capabilities(device, testFormat) & QImageIOPlugin::CanWrite)) {
  203. delete handler;
  204. handler = plugin->create(device, testFormat);
  205. break;
  206. }
  207. }
  208. }
  209. #endif // QT_NO_LIBRARY
  210. if (!handler)
  211. return 0;
  212. handler->setDevice(device);
  213. if (!testFormat.isEmpty())
  214. handler->setFormat(testFormat);
  215. return handler;
  216. }
  217. class QImageWriterPrivate
  218. {
  219. public:
  220. QImageWriterPrivate(QImageWriter *qq);
  221. // device
  222. QByteArray format;
  223. QIODevice *device;
  224. bool deleteDevice;
  225. QImageIOHandler *handler;
  226. // image options
  227. int quality;
  228. int compression;
  229. float gamma;
  230. QString description;
  231. QString text;
  232. // error
  233. QImageWriter::ImageWriterError imageWriterError;
  234. QString errorString;
  235. QImageWriter *q;
  236. };
  237. /*!
  238. \internal
  239. */
  240. QImageWriterPrivate::QImageWriterPrivate(QImageWriter *qq)
  241. {
  242. device = 0;
  243. deleteDevice = false;
  244. handler = 0;
  245. quality = -1;
  246. compression = 0;
  247. gamma = 0.0;
  248. imageWriterError = QImageWriter::UnknownError;
  249. errorString = QT_TRANSLATE_NOOP(QImageWriter, QLatin1String("Unknown error"));
  250. q = qq;
  251. }
  252. /*!
  253. Constructs an empty QImageWriter object. Before writing, you must
  254. call setFormat() to set an image format, then setDevice() or
  255. setFileName().
  256. */
  257. QImageWriter::QImageWriter()
  258. : d(new QImageWriterPrivate(this))
  259. {
  260. }
  261. /*!
  262. Constructs a QImageWriter object using the device \a device and
  263. image format \a format.
  264. */
  265. QImageWriter::QImageWriter(QIODevice *device, const QByteArray &format)
  266. : d(new QImageWriterPrivate(this))
  267. {
  268. d->device = device;
  269. d->format = format;
  270. }
  271. /*!
  272. Constructs a QImageWriter objects that will write to a file with
  273. the name \a fileName, using the image format \a format. If \a
  274. format is not provided, QImageWriter will detect the image format
  275. by inspecting the extension of \a fileName.
  276. */
  277. QImageWriter::QImageWriter(const QString &fileName, const QByteArray &format)
  278. : d(new QImageWriterPrivate(this))
  279. {
  280. QFile *file = new QFile(fileName);
  281. d->device = file;
  282. d->deleteDevice = true;
  283. d->format = format;
  284. }
  285. /*!
  286. Destructs the QImageWriter object.
  287. */
  288. QImageWriter::~QImageWriter()
  289. {
  290. if (d->deleteDevice)
  291. delete d->device;
  292. delete d->handler;
  293. delete d;
  294. }
  295. /*!
  296. Sets the format QImageWriter will use when writing images, to \a
  297. format. \a format is a case insensitive text string. Example:
  298. \snippet doc/src/snippets/code/src_gui_image_qimagewriter.cpp 0
  299. You can call supportedImageFormats() for the full list of formats
  300. QImageWriter supports.
  301. \sa format()
  302. */
  303. void QImageWriter::setFormat(const QByteArray &format)
  304. {
  305. d->format = format;
  306. }
  307. /*!
  308. Returns the format QImageWriter uses for writing images.
  309. \sa setFormat()
  310. */
  311. QByteArray QImageWriter::format() const
  312. {
  313. return d->format;
  314. }
  315. /*!
  316. Sets QImageWriter's device to \a device. If a device has already
  317. been set, the old device is removed from QImageWriter and is
  318. otherwise left unchanged.
  319. If the device is not already open, QImageWriter will attempt to
  320. open the device in \l QIODevice::WriteOnly mode by calling
  321. open(). Note that this does not work for certain devices, such as
  322. QProcess, QTcpSocket and QUdpSocket, where more logic is required
  323. to open the device.
  324. \sa device(), setFileName()
  325. */
  326. void QImageWriter::setDevice(QIODevice *device)
  327. {
  328. if (d->device && d->deleteDevice)
  329. delete d->device;
  330. d->device = device;
  331. d->deleteDevice = false;
  332. delete d->handler;
  333. d->handler = 0;
  334. }
  335. /*!
  336. Returns the device currently assigned to QImageWriter, or 0 if no
  337. device has been assigned.
  338. */
  339. QIODevice *QImageWriter::device() const
  340. {
  341. return d->device;
  342. }
  343. /*!
  344. Sets the file name of QImageWriter to \a fileName. Internally,
  345. QImageWriter will create a QFile and open it in \l
  346. QIODevice::WriteOnly mode, and use this file when writing images.
  347. \sa fileName(), setDevice()
  348. */
  349. void QImageWriter::setFileName(const QString &fileName)
  350. {
  351. setDevice(new QFile(fileName));
  352. d->deleteDevice = true;
  353. }
  354. /*!
  355. If the currently assigned device is a QFile, or if setFileName()
  356. has been called, this function returns the name of the file
  357. QImageWriter writes to. Otherwise (i.e., if no device has been
  358. assigned or the device is not a QFile), an empty QString is
  359. returned.
  360. \sa setFileName(), setDevice()
  361. */
  362. QString QImageWriter::fileName() const
  363. {
  364. QFile *file = qobject_cast<QFile *>(d->device);
  365. return file ? file->fileName() : QString();
  366. }
  367. /*!
  368. This is an image format specific function that sets the quality
  369. level of the image to \a quality. For image formats that do not
  370. support setting the quality, this value is ignored.
  371. The value range of \a quality depends on the image format. For
  372. example, the "jpeg" format supports a quality range from 0 (low
  373. quality, high compression) to 100 (high quality, low compression).
  374. \sa quality()
  375. */
  376. void QImageWriter::setQuality(int quality)
  377. {
  378. d->quality = quality;
  379. }
  380. /*!
  381. Returns the quality level of the image.
  382. \sa setQuality()
  383. */
  384. int QImageWriter::quality() const
  385. {
  386. return d->quality;
  387. }
  388. /*!
  389. This is an image format specific function that set the compression
  390. of an image. For image formats that do not support setting the
  391. compression, this value is ignored.
  392. The value range of \a compression depends on the image format. For
  393. example, the "tiff" format supports two values, 0(no compression) and
  394. 1(LZW-compression).
  395. \sa compression()
  396. */
  397. void QImageWriter::setCompression(int compression)
  398. {
  399. d->compression = compression;
  400. }
  401. /*!
  402. Returns the compression of the image.
  403. \sa setCompression()
  404. */
  405. int QImageWriter::compression() const
  406. {
  407. return d->compression;
  408. }
  409. /*!
  410. This is an image format specific function that sets the gamma
  411. level of the image to \a gamma. For image formats that do not
  412. support setting the gamma level, this value is ignored.
  413. The value range of \a gamma depends on the image format. For
  414. example, the "png" format supports a gamma range from 0.0 to 1.0.
  415. \sa quality()
  416. */
  417. void QImageWriter::setGamma(float gamma)
  418. {
  419. d->gamma = gamma;
  420. }
  421. /*!
  422. Returns the gamma level of the image.
  423. \sa setGamma()
  424. */
  425. float QImageWriter::gamma() const
  426. {
  427. return d->gamma;
  428. }
  429. /*!
  430. \obsolete
  431. Use setText() instead.
  432. This is an image format specific function that sets the
  433. description of the image to \a description. For image formats that
  434. do not support setting the description, this value is ignored.
  435. The contents of \a description depends on the image format.
  436. \sa description()
  437. */
  438. void QImageWriter::setDescription(const QString &description)
  439. {
  440. d->description = description;
  441. }
  442. /*!
  443. \obsolete
  444. Use QImageReader::text() instead.
  445. Returns the description of the image.
  446. \sa setDescription()
  447. */
  448. QString QImageWriter::description() const
  449. {
  450. return d->description;
  451. }
  452. /*!
  453. \since 4.1
  454. Sets the image text associated with the key \a key to
  455. \a text. This is useful for storing copyright information
  456. or other information about the image. Example:
  457. \snippet doc/src/snippets/code/src_gui_image_qimagewriter.cpp 1
  458. If you want to store a single block of data
  459. (e.g., a comment), you can pass an empty key, or use
  460. a generic key like "Description".
  461. The key and text will be embedded into the
  462. image data after calling write().
  463. Support for this option is implemented through
  464. QImageIOHandler::Description.
  465. \sa QImage::setText(), QImageReader::text()
  466. */
  467. void QImageWriter::setText(const QString &key, const QString &text)
  468. {
  469. if (!d->description.isEmpty())
  470. d->description += QLatin1String("\n\n");
  471. d->description += key.simplified() + QLatin1String(": ") + text.simplified();
  472. }
  473. /*!
  474. Returns true if QImageWriter can write the image; i.e., the image
  475. format is supported and the assigned device is open for reading.
  476. \sa write(), setDevice(), setFormat()
  477. */
  478. bool QImageWriter::canWrite() const
  479. {
  480. if (d->device && !d->handler && (d->handler = createWriteHandlerHelper(d->device, d->format)) == 0) {
  481. d->imageWriterError = QImageWriter::UnsupportedFormatError;
  482. d->errorString = QT_TRANSLATE_NOOP(QImageWriter,
  483. QLatin1String("Unsupported image format"));
  484. return false;
  485. }
  486. if (d->device && !d->device->isOpen())
  487. d->device->open(QIODevice::WriteOnly);
  488. if (!d->device || !d->device->isWritable()) {
  489. d->imageWriterError = QImageWriter::DeviceError;
  490. d->errorString = QT_TRANSLATE_NOOP(QImageWriter,
  491. QLatin1String("Device not writable"));
  492. return false;
  493. }
  494. return true;
  495. }
  496. /*!
  497. Writes the image \a image to the assigned device or file
  498. name. Returns true on success; otherwise returns false. If the
  499. operation fails, you can call error() to find the type of error
  500. that occurred, or errorString() to get a human readable
  501. description of the error.
  502. \sa canWrite(), error(), errorString()
  503. */
  504. bool QImageWriter::write(const QImage &image)
  505. {
  506. if (!canWrite())
  507. return false;
  508. if (d->handler->supportsOption(QImageIOHandler::Quality))
  509. d->handler->setOption(QImageIOHandler::Quality, d->quality);
  510. if (d->handler->supportsOption(QImageIOHandler::CompressionRatio))
  511. d->handler->setOption(QImageIOHandler::CompressionRatio, d->compression);
  512. if (d->handler->supportsOption(QImageIOHandler::Gamma))
  513. d->handler->setOption(QImageIOHandler::Gamma, d->gamma);
  514. if (!d->description.isEmpty() && d->handler->supportsOption(QImageIOHandler::Description))
  515. d->handler->setOption(QImageIOHandler::Description, d->description);
  516. if (!d->handler->write(image))
  517. return false;
  518. if (QFile *file = qobject_cast<QFile *>(d->device))
  519. file->flush();
  520. return true;
  521. }
  522. /*!
  523. Returns the type of error that last occurred.
  524. \sa ImageWriterError, errorString()
  525. */
  526. QImageWriter::ImageWriterError QImageWriter::error() const
  527. {
  528. return d->imageWriterError;
  529. }
  530. /*!
  531. Returns a human readable description of the last error that occurred.
  532. \sa error()
  533. */
  534. QString QImageWriter::errorString() const
  535. {
  536. return d->errorString;
  537. }
  538. /*!
  539. \since 4.2
  540. Returns true if the writer supports \a option; otherwise returns
  541. false.
  542. Different image formats support different options. Call this function to
  543. determine whether a certain option is supported by the current format. For
  544. example, the PNG format allows you to embed text into the image's metadata
  545. (see text()).
  546. \snippet doc/src/snippets/code/src_gui_image_qimagewriter.cpp 2
  547. Options can be tested after the writer has been associated with a format.
  548. \sa QImageReader::supportsOption(), setFormat()
  549. */
  550. bool QImageWriter::supportsOption(QImageIOHandler::ImageOption option) const
  551. {
  552. if (!d->handler && (d->handler = createWriteHandlerHelper(d->device, d->format)) == 0) {
  553. d->imageWriterError = QImageWriter::UnsupportedFormatError;
  554. d->errorString = QT_TRANSLATE_NOOP(QImageWriter,
  555. QLatin1String("Unsupported image format"));
  556. return false;
  557. }
  558. return d->handler->supportsOption(option);
  559. }
  560. /*!
  561. Returns the list of image formats supported by QImageWriter.
  562. By default, Qt can write the following formats:
  563. \table
  564. \header \o Format \o Description
  565. \row \o BMP \o Windows Bitmap
  566. \row \o JPG \o Joint Photographic Experts Group
  567. \row \o JPEG \o Joint Photographic Experts Group
  568. \row \o PNG \o Portable Network Graphics
  569. \row \o PPM \o Portable Pixmap
  570. \row \o TIFF \o Tagged Image File Format
  571. \row \o XBM \o X11 Bitmap
  572. \row \o XPM \o X11 Pixmap
  573. \endtable
  574. Reading and writing SVG files is supported through Qt's
  575. \l{QtSvg Module}{SVG Module}.
  576. Note that the QApplication instance must be created before this function is
  577. called.
  578. \sa setFormat(), QImageReader::supportedImageFormats(), QImageIOPlugin
  579. */
  580. QList<QByteArray> QImageWriter::supportedImageFormats()
  581. {
  582. QSet<QByteArray> formats;
  583. formats << "bmp";
  584. #ifndef QT_NO_IMAGEFORMAT_PPM
  585. formats << "ppm";
  586. #endif
  587. #ifndef QT_NO_IMAGEFORMAT_XBM
  588. formats << "xbm";
  589. #endif
  590. #ifndef QT_NO_IMAGEFORMAT_XPM
  591. formats << "xpm";
  592. #endif
  593. #ifndef QT_NO_IMAGEFORMAT_PNG
  594. formats << "png";
  595. #endif
  596. #ifndef QT_NO_IMAGEFORMAT_JPEG
  597. formats << "jpg" << "jpeg";
  598. #endif
  599. #ifndef QT_NO_IMAGEFORMAT_MNG
  600. formats << "mng";
  601. #endif
  602. #ifndef QT_NO_IMAGEFORMAT_TIFF
  603. formats << "tif" << "tiff";
  604. #endif
  605. #ifdef QT_BUILTIN_GIF_READER
  606. formats << "gif";
  607. #endif
  608. #ifndef QT_NO_LIBRARY
  609. QFactoryLoader *l = loader();
  610. QStringList keys = l->keys();
  611. for (int i = 0; i < keys.count(); ++i) {
  612. QImageIOPlugin *plugin = qobject_cast<QImageIOPlugin *>(l->instance(keys.at(i)));
  613. if (plugin && (plugin->capabilities(0, keys.at(i).toLatin1()) & QImageIOPlugin::CanWrite) != 0)
  614. formats << keys.at(i).toLatin1();
  615. }
  616. #endif // QT_NO_LIBRARY
  617. QList<QByteArray> sortedFormats;
  618. for (QSet<QByteArray>::ConstIterator it = formats.constBegin(); it != formats.constEnd(); ++it)
  619. sortedFormats << *it;
  620. qSort(sortedFormats);
  621. return sortedFormats;
  622. }
  623. QT_END_NAMESPACE