c++ - QImage:加载图像时自动检测格式
问题描述
我有一个带有.jpg
扩展名的图像,但它以png
格式存储。当我QImage
用来加载该图像时,它返回一个无效的QImage
:
QImage image (path);
if (image.isNull())
{
//it enters here
}
在加载图像之前,我必须一一检查格式:
auto readImage = [](const QString & path)
{
std::string formats[] = {
"PNG",
"JPG",
"GIF",
"JPEG",
};
for (auto && format : formats)
{
QImageReader img(path, format.c_str());
if (img.canRead())
{
return QImage(path, format.c_str());
}
}
return QImage(path);
};
QImage image = readImage(path);
if (image.isNull())
{
//it does not enter here this time
}
有没有更好的方法来加载未知格式的图像?
load
使用的方法更新QImage
,仍然得到相同的结果:
QImage image;
image.load(path);
if (image.isNull())
{
//it enters herer
}
解决方案
我认为这是您需要的(来自QImage 文档):
bool QImage::load(const QString &fileName, const char *format = nullptr) 从给定文件名的文件中加载图像。如果图像加载成功,则返回 true;否则使图像无效并返回 false。加载程序尝试使用指定的格式(例如 PNG 或 JPG)读取图像。如果未指定格式(这是默认设置),则会根据文件的后缀和标题自动检测。有关详细信息,请参阅 {QImageReader::setAutoDetectImageFormat()}{QImageReader}。
如果没有,请尝试查看这个答案,其中提到了 jpeg 插件丢失的选项?也许尝试使用 *.png 文件进行完全相同的实验?
推荐阅读
- javascript - 如何解决此错误:意外的令牌
- mysql - 创建包含动态数据透视表的存储过程时,如何让我的参数在动态数据透视表中工作?
- arduino - 如何从终端设备向 loRaWAN 中的多个应用程序服务器发送消息?
- laravel - 如何在 Laravel 的多维数组中使用同步函数
- javascript - Django 找不到灯箱和引导 js 文件。有人可以解决这个问题吗?
- c# - 在 Azure 中部署时出现 MIP SDK 错误 - SSL 失败内部异常:[http_exception: 'WinHttpSendRequest' CorrelationId.Description=PolicyProfile
- angular - 如何向下滚动到同一页面上的组件
- android - 如何用 Listview 和 Hero 动画实现图像(Flutter)
- c# - 如何以正确的方式将字节数组转换为 FormFile?
- javascript - 将类组件转换为功能组件时出现问题