QPixmap desktopPix = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId());
当然,如果用户的机器为双屏,需要根据需求自行处理,这里就不提了。
以上代码已经保存了一个图片,该图片为系统此时的桌面截图。
接下来,我们先进行压缩:
QByteArray byteTMP = QByteArray();
QImage image = desktopPix.toImage();
//将图片进行压缩成316*236大小
QPixmap pix = QPixmap::fromImage(image.scaled(316, 236, Qt::IgnoreAspectRatio));//再保存成数据流
QBuffer buffer(&byteTMP);buffer.open(QIODevice::WriteOnly);
pix.save(&buffer, "png", 0);
//Base64加密图片流
QByteArray byte64 = byteTMP.toBase64();
这样,byte64 就是我们想要得到的了。
base64与图片的加解密:
#ifndef SBASE64TOIMAGE_H
#define SBASE64TOIMAGE_H
#include <QByteArray>
#include <QBuffer>
#include <QImage>
#include <QPixmap>
class SBase64ToImage : public QObject
{
Q_OBJECT
public:
static QByteArray Image_To_Base64(QString ImgPath) {
QImage image(ImgPath);
QByteArray ba;
QBuffer buf(&ba);
image.save(&buf,"PNG",20);
QByteArray hexed = ba.toBase64();
buf.close();
return hexed;
}
static QPixmap Base64_To_Image(QByteArray bytearray) {
QByteArray Ret_bytearray = QByteArray::fromBase64(bytearray);
QBuffer buffer(&Ret_bytearray);
buffer.open(QIODevice::WriteOnly);
QPixmap imageresult;
imageresult.loadFromData(Ret_bytearray);
return imageresult;
}
};
#endif // SBASE64TOIMAGE_H