关于Qt绘制大图片无法显示的问题(缩放图片)

Qt在加载图片时会把图片存入缓存(QPixmapCache),有时候图片过大而电脑内存不足的时候,程序会出现崩溃,因此在处理图片的时候可以考虑将图片缩放。

本处采用QImageWriter去重新保存文件
在qt开发中很容易遇到用QPixmap绘制图片无法显示的问题,而图片却能在windows或者第三方工具下正常显示,
原因大部分是因为图片后缀被修改了,这种情况又无法去通过改回后缀名来避免。

因此,可以在读写文件的时候,直接去除后缀,通过解析图片文件本身去获取图片格式。

bool checkImageSize(const QString & path, const QSize & decSize)
{
	//检查文件是否存在
	if (!QFile::exists(path)) {
		qInfo() << QStringLiteral("无法找到该路径下的文件") << path;
		return false;
	}
	
	//检查文件是否为图片
	QImageReader reader(path);
	reader.setDecideFormatFromContent(true);
	if (!reader.canRead()) {
		qInfo() << QStringLiteral("图片文件无效");
		return false;
	}

	//宽高都小于指定大小则不处理
	auto size = reader.size();
	if (size.width() <= decSize.width() && size.height() <= decSize.height()) {
		return true;
	}
	
	//图片缩放到decSize尺寸
	size.scale(maxSize, Qt::KeepAspectRatio);
	reader.setScaledSize(size);
	
	//获取图片格式
	QByteArray imageFormat = QImageReader::imageFormat(path);
	
	//写图片文件
	QImageWriter writer(path, imageFormat);
	bool status = writer.write(reader.read());
	if (status) {
		return true;
	}

	qInfo() << QStringLiteral("处理失败")<< path;
	return false;
}

猜你喜欢

转载自blog.csdn.net/qq_36651243/article/details/107617522
今日推荐