将QImage转换为char *

时间:2018-03-19 08:43:43

标签: c++ image qt type-conversion

我捕获图像并使用QByteArray存储并保存图像:

QImage image(WEB_SCREENSHOT_WIDTH, page.viewportSize().height()/*65000,*/, QImage::Format_ARGB32_Premultiplied);
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");

我希望将QByteArray传递给char *并在函数末尾返回它,如下所示:

unsigned char* char_return = (unsigned char*)bytes.data();  

我必须这样做,因为我的其余程序是C base ...
但最后保存的文件无法打开
请帮帮我

修改
最小功能是这样的:

unsigned char* web_screenshot::get_web_image(){
  QImage image(WEB_SCREENSHOT_WIDTH, page.viewportSize().height(), QImage::Format_ARGB32_Premultiplied);
  QByteArray bytes;
  QBuffer buffer(&bytes);
  buffer.open(QIODevice::WriteOnly);
  image.save(&buffer, "PNG");
  unsigned char* char_return = (unsigned char*)bytes.data(); 
  return char_return;
}

1 个答案:

答案 0 :(得分:1)

像这样制作bytes.data()的深层副本:

unsigned char *data = (unsigned char *) malloc unsigned char(bytes.size());
memcpy(data, reinterpret_cast<unsigned char *>(bytes.data()), bytes.size());

<强>更新

下面,您可以看到一个功能示例,其中原始图像数据的副本用于加载UI上显示的新图像:

unsigned char* deepCopyImageData(int &size){
  QImage image("test.png"); // test image
  QByteArray bytes;
  QBuffer buffer(&bytes);
  buffer.open(QIODevice::WriteOnly);
  image.save(&buffer, "PNG");
  buffer.close();

  unsigned char *data = (unsigned char *) malloc(bytes.size());
  memcpy(data, reinterpret_cast<unsigned char *>(bytes.data()), bytes.size());
  size = bytes.size();
  return data;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    int size;
    unsigned char *data = deepCopyImageData(size);

    QImage image;
    if(!image.loadFromData(data,size))
        qWarning("Image loading failed");

    free(data); data = nullptr;
    QLabel *label = new QLabel();
    label->setPixmap(QPixmap::fromImage(image));
    label->show();

    return a.exec();
}