处理jpg图片后保持图片dpi
1、必须载入qjpeg.dll库
#include "mainwindow.h"
#include <QApplication>
#include "src/utils/utils.h"
int main(int argc, char *argv[])
{
printLog("载入qjpeg.dll库");
QString qjpeg("qjpeg.dll");
QLibrary qjpeglib(qjpeg.toUtf8().data());
if (qjpeglib.load())
{
printLog("成功载入有效jpeg驱动");
}
QApplication a(argc, argv);
MainWindow w;
w.showMaximized();
return a.exec();
}
qjpeg.dll库文件在“plugins\imageformats”下
例如我的:“D:\Qt\Qt5.12.2\5.12.2\mingw73_64\plugins\imageformats”
复制到项目路径下,例如我的就在项目路径下lib文件夹中。
2、QImage通过load加载图片并读取水平分辨率和垂直分辨率
/**
* @brief Picture::loadImage 载入图片
* @param fileName 图片路径
*/
void Picture::loadImage(const QString &fileName)
{
printLog("备份图片路径,保存的时候使用");
m_filePath = fileName;
printLog("读取Mat类型图片");
m_showImg = imread(fileName.toLocal8Bit().toStdString());
printLog("读取QPixmap类型图片");
if (!p_showImg.load(fileName)) {
printLog("如果读取QPixmap类型图片失败,则转换Mat类型为QPixmap类型");
p_showImg = Mat2Pixmap(m_showImg);
}
printLog("将QPixmap类型图片显示到控件");
m_item->setPixmap(p_showImg);
QImage i_showImg;
if (i_showImg.load(fileName))
{
printLog("读取水平分辨率和垂直分辨率");
dotsPerMeterX = i_showImg.dotsPerMeterX();
dotsPerMeterY = i_showImg.dotsPerMeterY();
printLog("dotsPerMeterX="+ QString::number(dotsPerMeterX) + ",dotsPerMeterY="+ QString::number(dotsPerMeterY));
}
else
{
dotsPerMeterX = 0;
dotsPerMeterY = 0;
}
}
如果没有“1、必须载入qjpeg.dll库”载入jpg图片就会失败
dotsPerMeterX = i_showImg.dotsPerMeterX();
dotsPerMeterY = i_showImg.dotsPerMeterY();
dotsPerMeterX和dotsPerMeterY即是水平分辨率和垂直分辨率
3、处理修改一下图片
例如擦除一下图片
printLog("擦除算法");
rectangle(m_showImg, Point(rect.x(),rect.y()), Point(rect.x() + rect.width(), rect.y() + rect.height()), Scalar(0xff,0xff,0xff), -1);
printLog("转换Mat类型为QPixmap类型");
p_showImg = Mat2Pixmap(m_showImg);
printLog("将QPixmap类型图片显示到控件");
m_item->setPixmap(p_showImg);
4、通过QImage设置水平分辨率和垂直分辨率并保存图片
/**
* @brief 保存图片
*/
void Picture::saveFile()
{
if (nullptr == m_item)
return;
QImage image = m_item->pixmap().toImage();
if (dotsPerMeterX == 0) {
dotsPerMeterX = 300 / 0.0254;
dotsPerMeterY = 300 / 0.0254;
printLog("获取原来的dpi失败,设置300 dpi");
}
image.setDotsPerMeterX(dotsPerMeterX);
image.setDotsPerMeterY(dotsPerMeterY);
image.save(m_filePath);
}