我捕获图像并使用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的...
但是最后保存的文件无法打开
请帮帮我
编辑:
最小功能是这样的:
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;
}
最佳答案
像这样深拷贝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();
}