Qt-加载错误扩展名的图像 [英] Qt - Loading image with wrong extension
问题描述
我目前正在开发一个Qt程序,该程序可以处理用户提供的图像.我遇到的一个问题是,许多图像使用错误的扩展名保存-例如图像以JPG格式保存,但扩展名为PNG.
I'm currently working on a Qt program that works with images that are supplied by the users. One problem I've run into is that a lot of images are saved with the wrong extension - e.g. an image is saved in JPG format but has a PNG extension.
Qt似乎不能很好地解决这一问题.当我将这样的图像加载到QImage中时,QImage无法加载.我一直在浏览文档,但没有遇到任何与此相关的信息.
Qt doesn't seem to deal well with this. When I load an image like this into a QImage, the QImage fails to load. I've been looking through the docs, but I haven't come across anything relating to this.
尽管使用了PNG扩展名,但我使用的其他程序仍能够正确地将图像识别为JPG,因此Qt应该没有理由无法做到这一点,但是我没有任何运气.
Other programs I've used are able to correctly identify the image as a JPG despite the PNG extension, so there should be no reason for Qt to be unable to do this, but I'm not having any luck.
有什么建议吗?
推荐答案
我通过使用QImageReader解决了这个问题.下面显示了使用PySide的示例.首先,我创建了一个QImageReader实例,并将其设置为从内容中读取格式.
I solved this by using a QImageReader. An example is shown below using PySide. First I created an instance of QImageReader and set it to read the format from the content.
image_reader = QtGui.QImageReader()
image_reader.setDecideFromContent(True)
此设置告诉读者仅查看图像数据来确定其格式,而不是扩展名.
This setting tells the reader to only look at the image's data to determine its format and not the extension.
然后,我将文件名设置为要加载的图像的文件名,并命名为read().
Then I set the filename to the filename of the image I wanted to load and called read().
image_reader.setFileName(file_path_here)
image = image_reader.read()
Read返回一个QImage对象,所以我从那里继续其余的代码.
Read returns a QImage object, so I proceeded with the rest of my code from there.
这篇关于Qt-加载错误扩展名的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!