get image type from qimage

3.3k views Asked by At

I'm trying to get the image type from a QImage as QString, here is the code I use:

QImageReader reader(filename);
QByteArray filetype_ba = reader.format();
QString filetype_qs(filetype_ba);

it works. But when I rename the file, for example from image.png to image.jpg, it returns empty values. Does it mean QImageReader reads from the filename and not the fileheader? I want to get the image type from header so even when I rename the file(not convert), it will still give me the right type.

2

There are 2 answers

2
UmNyobe On

QImageReader documentation specify the following steps:

  1. Image plugins are queried first, based on either the optional format string, or the file name suffix
  2. If no plugin supports the image format, Qt's built-in handlers are checked based on either the optional format string, or the file name suffix.
  3. If no capable plugins or built-in handlers are found, each plugin is tested by inspecting the content of the data stream.
  4. If no plugins could detect the image format based on data contents, each built-in image handler is tested by inspecting the contents.
  5. Finally, if all above approaches fail, QImageReader will report failure when trying to read the image.

It seems that a handler match the file extension, and say "hey I can totally read that" without checking the content, as you assumed. And by (good) design, the jpeg handler is supposed to handle only jpeg and nothing else.

The thing is QImage behaves differently, as it looks directly into the file data stream to guess the format. It seems like you should base your detection on Qimage mechanism alone.

Note: This describe the default behavior, which is is the same as QImageReader::setAutoDetectImageFormat(true). false means you, the programmer, should set the image type yourself using the second argument or another method.

0
ZDL-so On

QMimeDatabase::MatchContent

The file content is preferentially used to look for a match rather than file suffix.

QMimeType type = QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchContent);
QImage image("fileName", const_cast<char *>(type.preferredSuffix().toStdString().c_str()));