QPixmap编码成jpg的内存操作

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();
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值