bool QPixmap::save(const QString &fileName, const char *format = Q_NULLPTR, int quality = -1) const
多年前就知道QPixmap的save函数成员几乎可以保存成各种图像格式, 只要指定扩展名就行。
但一直比较不爽的是只能存成文件,如编码后数据用于网络传输,难道再读文件吗?就像曾经用过的libjpeg一样不能把编码后的数据存放在内存数组里。
今天在查看新版QT里有没有提供视频的编码功能时,在QT帮助文档里发现:
bool QPixmap::save(QIODevice *device, const char *format = Q_NULLPTR, int quality = -1) const
This is an overloaded function.
This function writes a QPixmap to the given device using the specified image file format and quality factor. This can be used, for example, to save a pixmap directly into a QByteArray:
QPixmap pixmap;
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format
看样子好像可以编码存到内存数组里了。赶紧一试,果然可以了。
bmp文件转成jpg,先存在内存数组里,再存到文件。
QPixmap map("/bb.bmp");
QByteArray ba;
QBuffer bf(&ba);
if (!map.save(&bf, "jpg"))
{
QMessageBox::critical(this, "error", "failed");
return;
}
QFile f("/bb.jpg");
f.open(QFile::WriteOnly);
f.write(ba);
f.close();
qDebug() << ba.size();