QImage - QByteArray - QString

QImage - QByteArray - QString (2009-04-02 11:25) 粘贴自pamire
分类: QT4




QByteArray 与 QString 之间的转换
#include <QCoreApplication>
#include <QImage>
#include <QFile>
#include <QByteArray>
#include <QBuffer>

int main(int argc, char *argv[])
{
      QCoreApplication app(argc, argv);
      
      QImage image("test.png");
      QByteArray ba;
      QBuffer buf(&ba);
      image.save(&buf, "BMP");
      
      QByteArray compressed = qCompress(ba, 1); // better just open file with QFile, load data, compress and toHex?
      QByteArray hexed = compressed.toHex();
      // save to a file
      QString str(hexed);
      QFile f("test.hex");
      if (f.exists())
          f.remove();
      if (f.open(QFile::WriteOnly))
      {
          f.write(str.toLatin1()); // holds only 0..f nothing special.
      }
      else
          qDebug("failed to open file \"test.hex\"");
      f.close();
      ----------
      if (f.open(QFile::ReadOnly))
      {
          QByteArray read = f.readAll();
          f.close();
          QString rStr = QString::fromLatin1(read.data(), read.size());
          if (rStr != str)
              qDebug("Writed and read two different hexed strings.");
          QByteArray readCompressed = QByteArray::fromHex(rStr.toAscii());
          if (readCompressed != compressed)
              qDebug("bytes before hexing and dehexing _is_ different.");
          QByteArray readDecompressed = qUncompress(readCompressed);
          if (readDecompressed != ba)
              qDebug("bytes before and after compressions are different.");
          QImage readImg;
          //QBuffer readBuf(&readDecompressed);
          readImg.loadFromData(readDecompressed);
          if (readImg.isNull())
              qDebug("The image is null. Something failed.");
          readImg.save("test.bmp");
      }
      else
          qDebug("failed to open test.hex file for reading");
      return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值